How to know if useQuery hit cache or network?

I’d like to execute a function (in this case a mutation) only once, when the query fetches from the network, and never execute that function again when it fetches from the cache.

Right now, with the code below, userSawDogPhoto is executed every time useQuery is completed, regardless if data is fetched from the network or from the cache.

const { loading, error, data } = useQuery(GET_DOG_PHOTO, {
   onCompleted() {
      userSawDogPhoto()
   } 
});

I’d like to run something similar to this:

const { loading, error, data, hitCache } = useQuery(GET_DOG_PHOTO, {
   onCompleted() {
      if(hitCache) {
         userSawDogPhoto()
      }
   } 
});

@apollo/client version: 3.3.11

@maieulchevalier Depending on your fetch policy, useQuery calls can both hit the cache and the network. So adding something like a hitCache property to the result could be confusing. I would recommend gating this yourself, in your code (e.g. use React state to control when useSawDogPhoto should be called).

1 Like