apollo-client

What does notifyOnNetworkStatusChange do exactly?


I had an issue where the loading property was not true when performing a refetch. I read somewhere notifyOnNetworkStatusChange to true would fix this.

However we've notice after using this property we have some use case where we end up in infinite refetch loop with no good explanation.

Can someone explain exactly what the notifyOnNetworkStatusChange do exactly on the useQuery hook? When should you use it, is there a particular fetch-policy you need to use in conjunction to it?


Solution

  • It seems like notifyOnNetworkStatusChange: true is to allow us check the current networkStatus of your useQuery, which is a number. Then based on the networkStatus variable we can choose our own strategy to render the current component.

    Important Note: loading will be undefined without notifyOnNetworkStatusChange: true

    The following code is from https://www.apollographql.com/docs/react/data/queries/#inspecting-loading-states

    import { NetworkStatus } from '@apollo/client';
    
    function DogPhoto({ breed }) {
      const { loading, error, data, refetch, networkStatus } = useQuery(
        GET_DOG_PHOTO,
        {
          variables: { breed },
          notifyOnNetworkStatusChange: true,
        },
      );
    
      if (networkStatus === NetworkStatus.refetch) return 'Refetching!';
      if (loading) return null;
      if (error) return `Error! ${error}`;
    
      return (
        <div>
          <img src={data.dog.displayImage} style={{ height: 100, width: 100 }} />
          <button onClick={() => refetch()}>Refetch!</button>
        </div>
      );
    }
    

    If you noticed the code

    if (networkStatus === NetworkStatus.refetch) return 'Refetching!', which means when refetch() is called the DogPhoto component will change to Retching! until it's done.

    The below link explained meaning of each number in networkstatus.

    https://github.com/apollographql/apollo-client/blob/master/src/core/networkStatus.ts#L4

    It's used to reflect the current status of your useQuery. Then based on the status, you can do further action upon it in case if things failed, but I believe you can always create your own solution without it.