我用createApi Fn创建了一个api端点。我需要将响应数据存储在localStorage中一段时间,并从LS获取它,而不是发出请求。当计时器超时时,使用useQuery更新数据。
export const geoApi = createApi({
reducerPath: 'geoApi',
baseQuery: fetchBaseQuery({ baseUrl: GEO_URL }),
endpoints: (builder) => ({
getData: builder.query<any, void>({
query: () => 'geo-data',
}),
}),
});
export const { useGetDataQuery } = geoApi;
我可以在组件逻辑(伪代码(内部使其:
let geoData = null;
const cachedData = ls.get('GEO_DATA');
if (cachedData && dataIsUpToDate()) {
geoData = cachedData;
} else {
const res = useGetDataQuery();
geoData = res.data;
updateCachedData(geoData);
}
但我想在redux存储逻辑中进行。
一段时间后,我建议使用钩子(根据您的情况进行修改(:
function useCachedData(key, ttl = Infinity, query) {
const [trigger] = query();
const [data, updateData] = useState();
const refreshCache = async () => {
const fetched = await trigger();
localStorage.setItem(key, JSON.stringify({ at: Date.now(), data: fetched.data });
updateData(fetched.data);
}
useEffect(() => {
const cached = localStorage.getItem(key);
let isValid = false;
if (cached) {
const { at, data } = JSON.parse(cached);
if (at + ttl > Date.now()) {
isValid = true;
updateData(data);
}
}
if (!isCached) {
refreshCache();
}
}, []);
return data;
}
懒惰查询的用法:
// ...component logic
const geoData = useCachedData('GEO_DATA', 60 * 1000, () => useLazyQuery());