反应查询:为什么这个查询总是过时?

react-query: why is this one query always stale?

我已经根据文档配置了具有无限陈旧时间的反应查询,如下所示:

    <ReactQueryConfigProvider config={{
        queries: {
            staleTime: Infinity
        }
    }}>

我的大部分查询都不会过时,除了一个,我的 'profile' 查询:

const getProfile = async () => {
    if (!isAuthenticated()) {
        return null;
    }
    try {
        const response = await axios.get('/user/profile');
        return response.data;
    }
    catch (error) {
        errorCheck(error);
    }
};

export const useProfile = () =>
    useQuery('profile', getProfile);

这是保存当前用户个人资料的查询。 isAuthenticated() 是一个同步调用,用于检查我们是否有用户令牌(所以我不会进行我知道会失败的 API 调用)。

出于某种原因,在 react-query devtools window 中,此查询立即显示为过时。我真的看不出我在这方面做了什么不同的事情。有什么调试建议吗?

我运行遇到了同样的问题,它是由一个组件引起的,该组件有一个使用react-query的子组件。检查您的组件树并确保在 <ReactQueryConfigProvider>.

之外没有使用 useProfile()

这是我认为的问题所在,以及我是如何解决的。

因为我在 ReactQueryConfigProider 中设置了 staleTime: Infinity,所以我希望我的所有查询都不会过时。

此查询的不同之处在于,当发生并非由 UI 驱动的事情时,我会使其无效。

我的代码中有一个会话计时器,当会话过期时,调用 queryCache.invalidateQueries('profile') 触发任何 UI 显示配置文件以重新呈现。

看来,如果 invalidateQueries 在查询上下文之外被调用,则不会观察到 ReactQueryConfigProider 中的设置,因此 staleTime 设置为默认值 0。

为了解决这个问题,对于我需要使计时器无效的查询,我明确地向查询添加了 { staletime: Infinity }

export const useProfile = () => {
    const { data: session } = useSession();
    const userId = session?.userId;
    return useQuery(['profile', userId], getProfile, { staleTime: Infinity });
};

我不会说这是 react-query 中的错误,但这似乎是一种解决方法。