import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useRef } from "react";
import { Todo } from "./hooks/useTodos";
import axios from "axios";
interface AddTodoContext {
previousTodo: Todo[];
}
const TodoForm = () => {
const queryClient = useQueryClient();
const addTodo = useMutation<Todo, Error, Todo, AddTodoContext>({
mutationFn: (todo: Todo) =>
axios
.post<Todo>("https://jsonplaceholder.typicode.com/todos", todo)
.then((res) => res.data),
onMutate: (newTodo: Todo) => {
const previousTodos = queryClient.getQueryData<Todo[]>(["todos"]) || [];
queryClient.setQueryData<Todo[]>(["todos"], (todos) => [
newTodo,
...(todos || []),
]);
if (ref.current) ref.current.value = "";
return { previousTodos };
},
onSuccess: (savedTodo, newTodo) => {
queryClient.setQueryData<Todo[]>(["todos"], (todos) =>
todos?.map((todo) => (todo === newTodo ? savedTodo : todo))
);
},
onError: (error, newTodo, context) => {
if (!context) return;
queryClient.setQueryData<Todo[]>(["todos"], context.previousTodo);
},
});
const ref = useRef<HTMLInputElement>(null);
return (
<>
{addTodo.error && (
<div className="alert alert-danger">{addTodo.error.message}</div>
)}
<form
className="row mb-3"
onSubmit={(event) => {
event.preventDefault();
if (ref.current && ref.current?.value) {
addTodo.mutate({
id: 0,
title: ref.current?.value,
completed: false,
userId: 1,
});
}
}}
>
<div className="col">
<input ref={ref} type="text" className="form-control" />
</div>
<div className="col">
<button className="btn btn-primary">Add</button>
</div>
</form>
</>
);
};
export default TodoForm;
我收到的错误是:
Type '(newTodo: Todo) => { previousTodos: Todo[]; }' is not assignable to type '(variables: Todo) => AddTodoContext | Promise<AddTodoContext | undefined> | undefined'.
Type '{ previousTodos: Todo[]; }' is not assignable to type 'AddTodoContext | Promise<AddTodoContext | undefined> | undefined'.ts(2322)
queryClient-bm-z2rsD.d.ts(598, 5): The expected type comes from property 'onMutate' which is declared here on type 'UseMutationOptions<Todo, Error, Todo, AddTodoContext>'
(property) onMutate?: ((variables: Todo) => AddTodoContext | Promise<AddTodoContext | undefined> | undefined) | undefined
您有一个简单的拼写错误:您的
onMutate
返回一个带有 previousTodos
(复数)的对象,但是您的 AddTodoContext
包含一个名为 previousTodo
(单数)的字段。