3
votes

I'm building an app using ApolloClient to query a GraphQL endpoint. I wish to utilize 'cache-and-network' fetch policy on normal queries since this particular policy only works for watchQueries. What I really want is the following:

  1. If we can query the server, we get a response from the server.

  2. If we can't query the server, we load the content from the cache, if it's cached

This is the code I'm using to instantiate the ApolloClient.

const defaultOptions = { 
  watchQuery: {
    fetchPolicy: 'cache-and-network',
    errorPolicy: 'ignore',
  },
  query: {
    fetchPolicy: 'network-only',
    errorPolicy: 'all',
  },
  mutate: {
    errorPolicy: 'all'
  }
}


const client = new ApolloClient({
  cache: cache,
  link: createUploadLink({
    uri: 'http://localhost:3000/graphql',
  }),
  defaultOptions
});

So I think I have two options: Catch the first query response and if failed load the contents from the cache, or use watchQuery method to issue the queries.

I have no idea were how to do it so any help would be welcome!

1
@Daniel Rearden thanks (again) for your help. I did not have much sleep last night trying to work this out.Bruno Tavares

1 Answers

3
votes

I ended up ignoring the defaultOptions object in the constructor. I define the fetchPolicy in the query itself, depending on the network status.

function getZones() {
  return ApolloService.client.query({
    query: GET_ZONES_CLIENT,
    fetchPolicy: navigator.onLine ? 'network-only' : 'cache-only'
  })
}