设置 onError 后,在 useMutation 的 onMutate 属性上使用 React 时出现未定义的错误(乐观更新)

问题描述 投票:0回答:1
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
reactjs react-query
1个回答
0
投票

您有一个简单的拼写错误:您的

onMutate
返回一个带有
previousTodos
(复数)的对象,但是您的
AddTodoContext
包含一个名为
previousTodo
(单数)的字段。

© www.soinside.com 2019 - 2024. All rights reserved.