我只是在玩 react-query
用打字稿
我的意思是我做我的第一次尝试
这是正确的方法吗?
const useCreateTodo = () => {
const queryClient = useQueryClient();
return useMutation(
(todo: TodoDto) => axios.post(`${URL}/todos`, todo).then((res) => res.data),
{
onMutate: async (newTodo: TodoDto) => {
// Cancel any outgoing refetches (so they don't overwrite our optimistic update)
await queryClient.cancelQueries("todos");
// Snapshot the previous value
const previousTodos = queryClient.getQueryData("todos");
// Optimistically update to the new value
queryClient.setQueryData<TodoDto[] | undefined>("todos", (old) =>
old ? [...old, newTodo] : old
);
// Return a context object with the snapshotted value
return { previousTodos };
},
// If the mutation fails, use the context returned from onMutate to roll back
onError: (
err,
newTodo,
context:
| {
previousTodos: unknown;
}
| undefined
) => {
queryClient.setQueryData(
"todos",
context ? context.previousTodos : context
);
},
// Always refetch after error or success:
onSettled: () => {
queryClient.invalidateQueries("todos");
},
}
);
};