reactjs - React-query:如何更新缓存?

标签 reactjs asynchronous async-await react-query

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

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

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

为了方便起见,我用 pokeapi 在 codesandbox 上做了一个小脚本:

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

如有任何帮助,我们将不胜感激!

最佳答案

那么,我将向您展示我的做法:

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); 

这一切都来自文档: Optimistic Updates

关于reactjs - React-query:如何更新缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65459419/

相关文章:

Python:url 内容的简单异步下载?

python asyncio双向通信硬件控制

javascript - 事件处理程序内的调用方法未定义

reactjs - (react-window) 如何将 props 传递给 <FixedSizeList>{Row}</FixedSizeList> 中的 {Row}

reactjs - react-testing-library - 使用 useContext Hook 的测试组件 - 上下文在测试之间持续存在

reactjs - 如何使用样式组件定位 Material UI Dialog 的背景颜色属性?

javascript - AngularJS:从函数返回数据并将其分配给变量

javascript - 为什么我使用异步钩子(Hook) API 会导致 Node.js 异常终止?

Node.JS MongoDB 找到 : Sequential faster than parallel, 为什么?

javascript - 为什么异步函数比同步函数需要更多时间来执行?