簡體   English   中英

如何讓 Apollo Client 重新獲取特定查詢?

[英]How to get that Apollo Client is refetching specific query?

應用程序中有幾個地方在不同的突變后重新獲取特定查詢。

例子:

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

在我的RecommendationsComponent中,我想知道這個查詢正在加載,但是useQueryloading在重新獲取getRecommendationsQuery時不會更新。

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

我可以嘗試將useQueryrefetch放到上下文中並在任何地方使用它而不是refetchQueries道具,但是有沒有更好的方法來實現這一點而沒有那個骯臟的黑客 - 要么使loading工作或使用 apollo 客戶端訂閱該信息?

useQuery Hook 只會調用 api 一次。 需要調用refetch function 才能再次調用

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

這也將更新loading state

對於這個問題,我在 github 中得到了兩個答案,將它們結合起來,終於奏效了:

notifyOnNetworkStatusChange: true傳遞給useQuery

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

將文檔而不是對象傳遞給 refetchQueries 道具:

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

當重新獲取查詢時,數據將被更新。 您可以訂閱useQuery鈎子返回的data object 的變化:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM