【问题标题】:setQueryData not updating the cache with React-QuerysetQueryData 不使用 React-Query 更新缓存
【发布时间】:2021-10-24 22:57:51
【问题描述】:

我有一个非常基本的应用程序,我正在尝试获取一些数据并更新缓存。例如,我尝试将数据更新为空数组,但在开发工具和控制台日志中,我不断获取旧数据

function App() {
  const queryClient = new QueryClient();
  const { isLoading, error, data } = useQuery('repoData', fetcher, {
    onSuccess: (data) => {
      queryClient.setQueryData('repoData', () => []);
    },
  });

  console.log('data', data);

  return (
    <div className="App">
      <Home />
    </div>
  );
}

更新缓存的正确方法是什么?

【问题讨论】:

    标签: javascript reactjs react-query


    【解决方案1】:

    为什么要更新您刚刚成功获取的同一项目的缓存? React-Query 会将fetcher 的结果放入从 useQuery 返回的数据字段中 - 您无需为此在 onSuccess 中执行任何操作

    【讨论】:

      【解决方案2】:

      这是官方文档中的示例。

       const queryClient = useQueryClient()
       
       const mutation = useMutation(editTodo, {
         onSuccess: data => {
           queryClient.setQueryData(['todo', { id: 5 }], data)
         }
       })
       
       mutation.mutate({
         id: 5,
         name: 'Do the laundry',
       })
       
       // The query below will be updated with the response from the
       // successful mutation
       const { status, data, error } = useQuery(['todo', { id: 5 }], fetchTodoById)
      

      https://react-query.tanstack.com/guides/updates-from-mutation-responses

      【讨论】:

        【解决方案3】:

        从您的fetcher 函数解析的数据将使用您选择的query keyreact-query 填充缓存。

        这些数据在解构useQuery 钩子时可用,或者在onSuccess 回调中可用。

        手动更新数据会很有用,如下所示: https://stackoverflow.com/a/68949327/1934484

        // fetcher function
        function getProducts() {
          // http call
          const { data } = await http.get<{ products: ProductT[] }>(/products);
        
          return data.products;
        }
        
        // data returned will be an array of products
        const { data } = useQuery('products', getProducts, {
          onSuccess: (data) => {
            // data returned will be an array of products
          },
        });
        

        【讨论】:

          猜你喜欢
          • 2023-02-03
          • 1970-01-01
          • 2022-11-17
          • 2021-02-14
          • 2022-11-22
          • 2022-12-15
          • 1970-01-01
          • 2018-09-11
          • 2017-07-10
          相关资源
          最近更新 更多