Don*_*al0 3 asynchronous async-await reactjs react-query
我有一个非常基本的应用程序,可以获取用户并允许更改他的名字。我使用 React 查询获取用户,这样我就可以从缓存功能中受益。有用。
但是,当我想更新用户时,我使用 axios 的经典 post 请求。一旦用户在数据库中更新,我需要直接在 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);
Run Code Online (Sandbox Code Playgroud)
这一切都来自文档: 乐观更新
| 归档时间: |
|
| 查看次数: |
6387 次 |
| 最近记录: |