我有一个非常基本的应用程序,我正在尝试获取一些数据,并更新缓存。例如,我尝试将数据更新到一个空数组中,但在开发工具和控制台日志中,我一直在获取旧数据
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>
);
}更新缓存的正确方法是什么?
发布于 2021-10-25 05:25:02
为什么要更新刚刚成功获取的同一项的缓存?React-Query会将fetcher的结果放入从useQuery返回的数据字段中-您不需要在onSuccess中执行任何操作
发布于 2021-10-29 07:35:17
从您的fetcher函数解析的数据将使用您选择的query key填充来自react-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
},
});发布于 2022-01-12 17:22:56
这是官方文档中的一个例子。
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
https://stackoverflow.com/questions/69701355
复制相似问题