我想在 useQuery
请求成功后设置 24 小时缓存。
但是一旦我刷新页面,缓存就消失了。我看到它是因为每次在我的服务器上命中路由时,我都会在 console.log 中记录一条消息。
如何防止这种行为并实现真正的缓存?
代码如下:
import { useQuery } from "react-query";
import { api } from "./config";
const _getUser = async () => {
try {
const res = api.get("/get-user");
return res;
} catch (err) {
return err;
}
};
export const getUser = () => {
const { data } = useQuery("contact", () => _getUser(), {
cacheTime: 1000 * 60 * 60 * 24,
});
return { user: data && data.data };
};
// then in the component:
const { user } = getUser();
return (
<div >
hello {user?.name}
</div>
我也尝试用 cacheTime
替换 staleTime
。
答案 0 :(得分:0)
如果你重新加载浏览器,缓存就会消失,因为缓存存在于内存中。如果你想要一个持久的缓存,你可以试试(实验性的)persistQueryClient 插件:https://react-query.tanstack.com/plugins/persistQueryClient