apollographql / apollo-feature-requests

🧑‍🚀 Apollo Client Feature Requests | (no 🐛 please).
Other
130 stars 7 forks source link

Refetch on window focus #422

Open tylerzey opened 7 months ago

tylerzey commented 7 months ago

Libraries such as SWR and React Query support opting into queries re-fetching upon the window being re-focused.

They allow to you configure this behavior on a per-query or on a global level. It seems quite popular and might be a feature Apollo would like to support.

Example from React Queries docs

useQuery({
  refetchOnWindowFocus: false,
})

A previous issue (feature request) had a lot of comments on it asking for Apollo to support the feature.

To implement this feature in Apollo current, you have to do the following.

On a global level:

const apolloClient = new ApolloClient();

window.addEventListener('focus', () => {
  apolloClient.refetchQueries({ include: 'active' });
});

On a per-query level:

https://github.com/apollographql/apollo-feature-requests/issues/247#issuecomment-1063411159

Specifically:

  const { isWindowFocused } = useWindowFocus();

  useEffect(() => {
    if (!isWindowFocused) {
      stopPolling();
    } else {
      // Refetch data immediately when the window is refocused.
      refetch?.();
      startPolling(pollInterval);
    }
  }, [isWindowFocused, pollInterval, refetch, startPolling, stopPolling]);

The use case seems fairly common and might be something to consider bringing into Apollo as a feature.

nwazuo commented 5 months ago

+1 for this

shyamayadav154 commented 5 months ago

+1

optimistic-updt commented 3 months ago

+1

rajat-sr commented 2 months ago

+1

stanislavyv commented 2 months ago

+1

man-trackunit commented 1 month ago

+2

KMKoushik commented 6 days ago

This is how I do it right now. this code will be added globally where we include apollo provider

useEffect(() => {
    const refetchQueries = () => {
      if (document.visibilityState === "visible") {
        client.refetchQueries({ include: "active" });
      }
    };

    window.addEventListener("visibilitychange", refetchQueries);

    return () => {
      window.removeEventListener("visibilitychange", refetchQueries);
    };
  }, []);