首页 > 解决方案 > 可以通过 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 但两种解决方案似乎都没有按计划工作,即如果缓存数据在刷新间隔内,则使用缓存数据。

标签: reactjsnext.jsswr

解决方案


推荐阅读