reactjs - 可以通过 useSWR 钩子在 fetcher 中使用缓存的时间戳吗?
问题描述
我在使用 useSWR 钩子时遇到问题,要么是由于在多个位置 onMount 被触发而获取太多次,要么是因为它第一次没有在 onMount 上运行而失败。
我的想法是简单地检查 fetcher 内的缓存,看看在刷新间隔内是否已经有一个值,然后将它发送回来,这似乎有效,但我不能 100% 确定它是否会在 mutate 后按我的意图工作被外部调用......我是否忽略了为什么我不应该使用这种方法?
基本上 mutate(url) 如果在刷新间隔内调用它,它将变得与 mutate(url, false) 相同,我认为这很好,但理想情况下我希望它正常工作。
const getTimestampKey = (key: string) => key + "--ts";
const hasExpired = (key: string) => {
const timestampKey = getTimestampKey(key);
if (!cache.has(timestampKey)) return true;
let prevTime = cache.get(timestampKey);
return Date.now() > prevTime + RefreshInterval;
};
const saveTimestamp = (key: string) => {
const timestampKey = getTimestampKey(key);
cache.set(timestampKey, Date.now());
};
export const getApplicationsByAssociationKey = (selectedAssociationId: string) => {
return `${applicationsUrl}?associationId=${selectedAssociationId}`;
};
export const getUserApplicationsFetcher = (url: string) => {
if (!url) throw new Error("Bad argument exception.");
if (!hasExpired(url)) {
let cachedData = cache.get(url);
if (cachedData) return cachedData;
}
return bffClient
.get<ApplicationsResponseArray>(url, { withCredentials: true })
.then((res) => {
saveTimestamp(url); // save the timestamp
return res.data;
});
};
export const useGetUserApplicationsByAssociationId = (selectedAssociationId: string) => {
const { data, error, mutate, isValidating } = useSWR<ApplicationsResponseArray, any>(
selectedAssociationId ? getApplicationsByAssociationKey(selectedAssociationId) : null,
getUserApplicationsFetcher,
{
refreshInterval: RefreshInterval
}
);
return {
data: (data || []) as Application[],
error: error,
loading: !data && !error,
mutate: mutate
};
};
我尝试过的选项都是:
refreshInterval:RefreshInterval, revalidateOnMount:false, revalidateOnFocus:false, revalidateOnReconnect:false, refreshWhenOffline:false, refreshWhenHidden:false
或允许 revalidateOnMount 但再次尝试 onError 但两种解决方案似乎都没有按计划工作,即如果缓存数据在刷新间隔内,则使用缓存数据。
解决方案
推荐阅读
- microsoft-graph-api - 在 MS Graph API 的身份验证过程之后,是否有任何获取用户唯一身份的方法?
- ios - iOS:创建可扩展标签
- python - 如何将在引导模式中输入的数据保存到另一个模型中
- jquery - 单击按钮时按空格键
- javascript - javascript 错误:arguments[0].setAttribute 不是函数
- ios - 如何在快速关闭第二个视图控制器后启用带有视图的自定义视图控制器
- python - 如何在绘图条形图上左对齐文本(包含示例图像)[Plotly-Dash]
- php - 如何使用mysqli php从多个表中输出所有数据
- c# - 为什么 fontawesome 图标没有应用于 gridview 图标?
- elasticsearch - 在弹性搜索的索引中查找唯一文档