【问题标题】:React-query: how to update the cache?React-query:如何更新缓存?
【发布时间】:2021-11-20 10:15:22
【问题描述】:

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

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

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

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

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

任何帮助将不胜感激!

【问题讨论】:

    标签: reactjs asynchronous async-await react-query


    【解决方案1】:

    那么,我会告诉你我的工作:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 2022-11-17
      • 2021-06-26
      • 2021-07-01
      • 2017-10-03
      • 2021-07-30
      • 2021-11-13
      相关资源
      最近更新 更多