reactjs - React-query:如何更新缓存?
问题描述
我有一个非常基本的应用程序,它可以获取用户并允许更改他的名字。我使用 React 查询获取用户,因此我可以从缓存功能中受益。有用。
但是,当我想更新用户时,我使用带有 axios 的经典发布请求。一旦用户在数据库中更新,我需要直接在 updateUser() 函数中更新缓存。我在网上看到过使用 queryCache.setCache 的教程,但在这里不起作用。如何解决这个问题?或者也许有更好的方法来处理此类查询?
此外,我注意到大量渲染......(请参阅应用程序文件中的“用户渲染”console.log)。
为方便起见,我在带有 pokeapi 的代码盒上制作了一个小脚本:
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);
这一切都来自文档: 乐观更新
推荐阅读
- angular - 用户代理嗅探分配模板时出错
- javascript - 排除正则表达式匹配组中的特殊字符
- javascript - Angular 2搜索(添加项目,删除项目,选择所有项目到数组)依赖
- jquery - jquery点击更改背景图片url功能
- stripe-payments - 修改 Stripe 订阅状态
- macos - Vim 似乎没有从安装在 .vim/pack 文件夹中的包中加载语法
- selenium - 当我打开谷歌页面时,每次发生错误。无法创建新的远程会话
- wordpress - 在 WordPress 的类别中显示带有 And 关系的帖子
- spring-data-jpa - Java Spring JPA本机查询SQL注入证明吗?
- c - C 条件技巧