首页 > 解决方案 > React-query:如何更新缓存?

问题描述

我有一个非常基本的应用程序,它可以获取用户并允许更改他的名字。我使用 React 查询获取用户,因此我可以从缓存功能中受益。有用。

但是,当我想更新用户时,我使用带有 axios 的经典发布请求。一旦用户在数据库中更新,我需要直接在 updateUser() 函数中更新缓存。我在网上看到过使用 queryCache.setCache 的教程,但在这里不起作用。如何解决这个问题?或者也许有更好的方法来处理此类查询?

此外,我注意到大量渲染......(请参阅应用程序文件中的“用户渲染”console.log)。

为方便起见,我在带有 pokeapi 的代码盒上制作了一个小脚本:

https://codesandbox.io/s/api-service-syxl8?file=/src/App.js:295-306

任何帮助将不胜感激!

标签: reactjsasynchronousasync-awaitreact-query

解决方案


因此,我将向您展示我的工作:

const updateUser = async (userUpdates: User) => {
  const data = await UserService.updateUser(userUpdates); // return axios data

  return data;
}

// if you want optimistic updating:
const { mutate: mutateUser } = useMutation(updateUser, {
    onMutate: async (userUpdates) => {
      // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
      await queryClient.cancelQueries(['user', userUpdates.id]);

      // Snapshot the previous value
      const previousUser = queryClient.getQueryData(['user', userUpdates.id]);

      // Optimistically update to the new value
      queryClient.setQueryData(['user', userUpdates.id], userUpdates);

      // Return a context with the previous user and updated user
      return { previousUser, userUpdates }; // context
    },
    // If the mutation fails, use the context we returned above
    onError: (err, userUpdates, context) => {
      queryClient.setQueryData(['user', context.userUpdates.id], context.previousUser);
    },
    // Always refetch after error or success:
    onSettled: (userUpdates) => {
      queryClient.invalidateQueries(['user', userUpdates.id]);
    }
  });

// then to update the user
const handleUpdateUser = (userUpdates: User) => mutateUser(userUpdates); 

这一切都来自文档: 乐观更新


推荐阅读