When does useQuery think that a query is "loading"?

Here’s a component that calls useQuery() to get data from an async local resolver. The resolver waits a second, then returns some hardcoded data. I was expecting that useQuery().loading === true until the resolver completed, but that doesn’t seem to be the case.

// resolver
export async function todos() {
  console.log("waiting 1000ms");
  await wait(1000);
  console.log("waiting complete");
  return await Object.values(db.todos);
}

// component
export default function Todos() {
  const { loading, refetch } = useQuery(Queries.GET_ALL_TODOS);
  console.log({ loading });
  if (loading) return "Loading...";
  return (
    <>
      <span>"Data loaded..."</span>
      <button
        onClick={() => {
          refetch();
        }}
      >
        Reload data
      </button>
    </>
  );
}

you can see that clicking the button triggers a refetch, which does trigger the resolver, which waits a second to log a message, but the loading state is never changed.

is that surprising?

Hello! By default, a component doesn’t rerender during the phases of a query refetch. To enable this behavior, pass the notifyOnNetworkStatusChange option to useQuery, like so:

const { loading, refetch } = useQuery(Queries.GET_ALL_TODOS, {
  notifyOnNetworkStatusChange: true
});

For more information, see Inspecting loading states.

great, that’s cool! but it doesn’t look like notifyOnNetworkStatusChange is useful for the refetchQueries: [] option on useMutation(). maybe what i need to do in that case is:

const [refetch] = useQuery(MY_QUERY, {
  notifyOnNetworkStatusChange: true
})
useMutation(SOME_MUTATION, {
  refetchQueries: [{query: MY_QUERY}] // this runs the query but doesn't seem to notify me with the network status
  onCompleted: () => refetch() // i guess this has the desired effect, i'm not sure what the difference is
})

Ah! Yes, this is currently an exceptional case and your solution should work.

Your issue is rather timely, as improvements to refetching queries after a mutation are coming in Apollo Client 3.4 (just-merged PR). This new API should honor options like notifyOnNetworkStatusChange, and it will enable you to make other modifications to queries before they’re refetched.

1 Like