React-apollo: useQuery keeps polling

Created on 24 Jul 2019  ·  6Comments  ·  Source: apollographql/react-apollo

Just noticed when using the useQuery hook with a poll interval, the polling continues even when navigating to another page / hiding the component with the query in.

Intended outcome:

The polling should stop when navigating away from the page with the query component / when the component is hidden (via state for example)

Actual outcome:

Polling continues

How to reproduce the issue:

https://codesandbox.io/s/apollo-react-query-component-f49si?fontsize=14

Click button to hide the component then check the network calls

Version

@apollo/react-hooks - 0.1.0-beta.11

Most helpful comment

I'm using this workaround.

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

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

All 6 comments

I also reproduced this bug.
I have prepared PR to fix this https://github.com/apollographql/react-apollo/pull/3273
My reproduce: https://codesandbox.io/s/apolloreact-hooksusequerybug-ympqk

I'm using this workaround.

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

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

@proutek Why do you need update effect when links to functions startPolling and stopPolling are changing?

I am not sure is there a logic behind useQuery but for my vision these function should not be changed in any case, so this effect would be pretty enough.

useEffect(() => {
    startPolling(5000); // will be called only once
    return stopPolling; // just return cleanup function without making new one
  }, []);

Then effect will be

Yes, you're right. I tried it before with empty array. I just wanted to get rid off the compiler warning.

Compiled with warnings.

./src/components/Shipping/ShippingActive.tsx
  Line 30:  React Hook useEffect has missing dependencies: 'startPolling' and 'stopPolling'. Either include them or remove the dependency array  react-hooks/exhaustive-deps

Maybe I could try something like this https://github.com/facebook/create-react-app/issues/6880

@proutek the thing is, this lint rule is cool for check yourself with dependencies but it's not much smart to separate them as required and not required because there is no checking types and logic behind our code.
I am coding without this rule but I must be careful with dependencies.

Here is the code work for me, but I am not sure it is the correct way or not.

const { data, error, loading, stopPolling } = useQuery(GET_INVENTORY_DATA, {
    pollInterval: 500
  });

  useEffect(() => {
    return () => {
      stopPolling();
    };
  });

Was this page helpful?
0 / 5 - 0 ratings