Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
Paul Razvan Berg Avatar asked Nov 02 '19 18:11

Paul Razvan Berg


People also ask

How do you Refetch a useQuery?

If you want to refetch multiple entities you could have a top level useState that is called for instance fetchAll and: ... const query = useQuery(["endpoint", fetch, fetchAll], fetchData); ... and this code will also trigger if you press a button to fetch all.

What is difference between useQuery and useLazyQuery?

Unlike with useQuery , when you call useLazyQuery , it does not immediately execute its associated query. Instead, it returns a query function in its result tuple that you call whenever you're ready to execute the query. Click me!

How do I disable Apollo cache?

If you really want to disable the cache, read and write, use no-cache . Which is "similar to network-only, except the query's result is not stored in the cache."


Video Answer


2 Answers

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.

like image 161
Greg Brodzik Avatar answered Sep 28 '22 05:09

Greg Brodzik


This is an code example :

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

 useEffect(() => {
     startPolling(5000)
   return () => {
    stopPolling()
   }
 }, [startPolling, stopPolling])
like image 36
anandharshan Avatar answered Sep 28 '22 05:09

anandharshan