如何让 Apollo Client 重新获取特定查询?

How to get that Apollo Client is refetching specific query?

应用程序中有几个地方在不同的变更后重新获取特定查询。

示例:

// Some component
const [setUserLocation, setUserLocationResult] = useMutation(setUserLocationMutation, {
  refetchQueries: [{ query: getRecommendationsQuery }],
});

在我的 RecommendationsComponent 中,我想知道此查询正在加载,但是 useQueryloadinggetRecommendationsQuery 重新获取时不会更新。

const {
  data,
  loading, // this loading is false all the time except first loading
} = useQuery(getRecommendationsQuery);

我可以尝试将 useQueryrefetch 放到上下文中并在任何地方使用它而不是 refetchQueries prop,但是有没有更好的方法来实现这一点而没有那个肮脏的黑客- 使 loading 工作或使用 apollo 客户端订阅该信息?

重新获取查询时,将更新数据。您可以订阅从 useQuery 挂钩返回的 data 对象中的更改:

const {
  data,
  loading,
} = useQuery(getRecommendationsQuery);

useEffect(() => {
  console.debug("data has changed!", data]);
}, [data]);

试试这个:

import { NetworkStatus, useQuery } from '@apollo/client';

...

const { data, networkStatus, error } = useQuery(QUERY_DOC);

...

const isRefetching = networkStatus === NetworkStatus.refetch;

useQuery Hook 只会调用一次 api。需要调用refetch函数再调用

const {
  data,
  loading, 
  refetch: getRecommendations // <- use this function to refetch the data
} = useQuery(getRecommendationsQuery);

这也会更新 loading 状态

对于那个问题,我在 github 中得到了两个 answers,将它们结合起来,最终成功了:

notifyOnNetworkStatusChange: true传递给useQuery:

const { data, loading } = useQuery(getRecommendationsQuery, {
  notifyOnNetworkStatusChange: true
});

将文档而不是对象传递给 refetchQueries 属性:

// Some component
const [setUserLocation, setUserLocationResult] = useMutation(setUserLocationMutation, {
  refetchQueries: [getRecommendationsQuery],
});