Paul Razvan Berg
Paul Razvan Berg

Reputation: 21348

How to switch polling on and off in Apollo?

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?

Upvotes: 11

Views: 19618

Answers (2)

anandharshan
anandharshan

Reputation: 6342

This is an code example :

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

 useEffect(() => {
     startPolling(5000)
   return () => {
    stopPolling()
   }
 }, [startPolling, stopPolling])

Upvotes: 13

Greg Brodzik
Greg Brodzik

Reputation: 1817

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.

Upvotes: 15

Related Questions