反应查询突变打字稿

时间:2021-01-17 11:43:16

标签: reactjs react-query

我只是在玩 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");
      },
    }
  );
};

对不起:) Lorem Ipsum 只是印刷和排版行业的虚拟文本。 Lorem Ipsum 一直是业界标准的虚拟文本

1 个答案:

答案 0 :(得分:2)

乐观更新对于类型推断来说有点棘手。现在有一个例子来说明这个确切的情况 reprex package

从那个例子:

$productCategory= new ProductCategory();
$productCategory->cat_name='test'; // if the is another required attributes, fill them.
$productCategory->save();
$product->categories()->attach($productCategory->id);

几个解释:

  • 基本上,您只想在 library(tidyverse) names1a <- c("Name Alperton plc", "Bury", "Central", "Durham") names1a <- str_replace_all(names1a, "Name ", "") names1a <- str_replace_all(names1a, " plc", "") names1a <- paste0("Name ", names1a, " plc") names1a #> [1] "Name Alperton plc" "Name Bury plc" "Name Central plc" #> [4] "Name Durham plc" 上设置类型定义,以便类型推断适用于 const addTodoMutation = useMutation( newTodo => axios.post('/api/data', { text: newTodo }), { // When mutate is called: onMutate: async (newTodo: string) => { setText('') // 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>('todos') // Optimistically update to the new value if (previousTodos) { queryClient.setQueryData<Todos>('todos', { ...previousTodos, items: [ ...previousTodos.items, { id: Math.random().toString(), text: newTodo }, ], }) } return { previousTodos } }, // If the mutation fails, use the context returned from onMutate to roll back onError: (err, variables, context) => { if (context?.previousTodos) { queryClient.setQueryData<Todos>('todos', context.previousTodos) } }, // Always refetch after error or success: onSettled: () => { queryClient.invalidateQueries('todos') }, } ) (推断出onMutate)以及 mutateFn 中的上下文{1}}。
  • newTodo 添加泛型,以便输入 onError。不过,您不需要与 getQueryData 联合 - react-query 会为您完成。
  • previousTodos 的函数式更新程序很棘手,因为它要求您返回一个数组,但 undefined 可以是未定义的。我更喜欢使用 setQueryData
  • 返回的 old