Disable short polling for RTK Query on window not focused and revalidate on resume focus

Viewed 14

I am using Redux Toolkit with RTK Query to manage the API calls and states in my React application.

For a particular API, I am trying to mimic a real-time update effect with short polling, and calling the API defined in the API reducer by,

  const { data, error, isLoading } = useGetAPIQuery(
    {},
    { pollingInterval: 5000 }
  );

However, I want the short polling to stop when the user has left the window, such as switching the focused tab to another tab, and revalidating the data once the window is focused again.

Is this possible with RTK query?

Similiar question also asked as issue posted on Github

1 Answers

Sure, you can use a package like use-window-focus to detect the focus.

  const windowFocused = useWindowFocus();
  const { data, error, isLoading } = useGetAPIQuery(
    {},
    { pollingInterval: windowFocused  ? 5000 : false }
  );
Related