Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refetch on window focus #422

Open
tylerzey opened this issue Jan 31, 2024 · 8 comments
Open

Refetch on window focus #422

tylerzey opened this issue Jan 31, 2024 · 8 comments
Labels
core Feature requests related to core functionality

Comments

@tylerzey
Copy link

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:

#247 (comment)

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.

@jerelmiller jerelmiller added the core Feature requests related to core functionality label Jan 31, 2024
@nwazuo
Copy link

nwazuo commented Mar 13, 2024

+1 for this

@shyamayadav154
Copy link

+1

3 similar comments
@optimistic-updt
Copy link

+1

@rajat-sr
Copy link

+1

@stanislavyv
Copy link

+1

@man-trackunit
Copy link

+2

@KMKoushik
Copy link

KMKoushik commented Aug 30, 2024

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);
    };
  }, []);

@nextglabs
Copy link

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
core Feature requests related to core functionality
Projects
None yet
Development

No branches or pull requests

10 participants