可以在带有 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:刷新间隔, revalidateOnMount:假, revalidateOnFocus:假, revalidateOnReconnect:假, refreshWhenOffline:假, refreshWhenHidden:假

或允许 revalidateOnMount 但再次尝试 onError 但两种解决方案似乎都没有按计划工作,即在刷新间隔内使用缓存数据。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...