82 lines
2.2 KiB
TypeScript
82 lines
2.2 KiB
TypeScript
import { useQuery, useMutation, useQueryClient } from 'react-query';
|
|
import api from '../services/api';
|
|
import { Tarefa } from '../types/entities';
|
|
|
|
export const useTarefas = () => {
|
|
const queryClient = useQueryClient();
|
|
|
|
const { data: tarefas = [], isLoading } = useQuery<Tarefa[]>('tarefas', async () => {
|
|
const response = await api.get('/tarefas');
|
|
return response.data;
|
|
});
|
|
|
|
const createTarefa = useMutation(
|
|
async (data: Partial<Tarefa>) => {
|
|
const response = await api.post('/tarefas', data);
|
|
return response.data;
|
|
},
|
|
{
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries('tarefas');
|
|
}
|
|
}
|
|
);
|
|
|
|
const updateTarefa = useMutation(
|
|
async ({ id, data }: { id: string; data: Partial<Tarefa> }) => {
|
|
const response = await api.put(`/tarefas/${id}`, data);
|
|
return response.data;
|
|
},
|
|
{
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries('tarefas');
|
|
}
|
|
}
|
|
);
|
|
|
|
const updateStatus = useMutation(
|
|
async ({ id, status, progresso }: { id: string; status: string; progresso?: number }) => {
|
|
const response = await api.patch(`/tarefas/${id}/status`, { status, progresso });
|
|
return response.data;
|
|
},
|
|
{
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries('tarefas');
|
|
}
|
|
}
|
|
);
|
|
|
|
const deleteTarefa = useMutation(
|
|
async (id: string) => {
|
|
await api.delete(`/tarefas/${id}`); // Remover o /api duplicado
|
|
},
|
|
{
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries('tarefas');
|
|
},
|
|
onMutate: async (deletedId) => {
|
|
await queryClient.cancelQueries('tarefas');
|
|
const previousTarefas = queryClient.getQueryData<any[]>('tarefas');
|
|
queryClient.setQueryData('tarefas', (old: any[] = []) =>
|
|
old.filter(tarefa => tarefa.id !== deletedId)
|
|
);
|
|
return { previousTarefas };
|
|
},
|
|
onError: (err, variables, context: any) => {
|
|
if (context?.previousTarefas) {
|
|
queryClient.setQueryData('tarefas', context.previousTarefas);
|
|
}
|
|
}
|
|
}
|
|
);
|
|
|
|
return {
|
|
tarefas,
|
|
isLoading,
|
|
createTarefa,
|
|
updateTarefa,
|
|
updateStatus,
|
|
deleteTarefa
|
|
};
|
|
};
|