9

I use the useQuery Hook like this:


function Foo() {
  const { data, error, loading } = useQuery(MY_QUERY, { pollInterval: 1000 });

  return (
    <>
      <Bar/>
      <Baz/>
      {data}
    </>
  );
}

Now, both Bar and Baz use the same query. Baz is a sidebar and I'd like to disable the polling while it is active.

I have a global reducer for handling the state of Baz and I modified it like this:

if (isSidebarOpen === false) {
  ...
  apolloClient.stop();
} else {
  // TODO
}

This stops the polling, but I don't know how to reactivate it when the sidebar gets closed (that is, in the else block above).

Am I doing this correctly? Is there a different way to toggle the polling of a GraphQL query with Apollo?

Paul Razvan Berg
  • 16,949
  • 9
  • 76
  • 114

2 Answers2

13

You can start and stop polling dynamically with the startPolling and stopPolling functions that are returned by the useQuery hook. For more information, you can see the docs here.

Greg Brodzik
  • 1,765
  • 7
  • 9
  • If polling does not work, check if you have set `ssr` to `true` on your Apollo client. Polling is not supported if server side rendering is enabled. – Frederik Kammer May 25 '22 at 15:44
11

This is an code example :

const { loading, error, data, startPolling, stopPolling } = useQuery(GET_DELIVERIES_QUERY)

 useEffect(() => {
     startPolling(5000)
   return () => {
    stopPolling()
   }
 }, [startPolling, stopPolling])
anandharshan
  • 5,817
  • 4
  • 34
  • 33
  • 4
    Thank you! Apollo really should add in their documentation that if you add pollInterval to your useQuery, it will never stop! Your code worked perfectly for only polling when that component is visible. – Craigo Mar 03 '21 at 01:16
  • they have. https://www.apollographql.com/docs/react/data/queries/#polling. `Note that if you set pollInterval to 0, the query does not poll.`. the example doesn't illustrate `startPolling` and `stopPolling` though – shamanth Gowdra Shankaramurthy Nov 02 '22 at 21:00