79

I'm using apollo-client, apollo-link and react-apollo, I want to fully disable cache, but don't know how to do it.

I read the source of apollo-cache-inmemory, it has a config argument in its constructor, but I can't build a dummy storeFactory to make it works.

Jacky Lee
  • 1,082
  • 1
  • 8
  • 11
  • 2
    Checkout [fetchPolicy](https://www.apollographql.com/docs/react/basics/queries.html#graphql-config-options-fetchPolicy) and set it to `network-only`. – Robin Wieruch Feb 01 '18 at 19:19

3 Answers3

156

You can set defaultOptions to your client like this:

const defaultOptions: DefaultOptions = {
      watchQuery: {
        fetchPolicy: 'no-cache',
        errorPolicy: 'ignore',
      },
      query: {
        fetchPolicy: 'no-cache',
        errorPolicy: 'all',
      },
    }

const client = new ApolloClient({
    link: concat(authMiddleware, httpLink),
    cache: new InMemoryCache(),
    defaultOptions: defaultOptions,

});

fetchPolicy as no-cache avoids using the cache.

See https://www.apollographql.com/docs/react/api/core/ApolloClient/#defaultoptions

Omar Dulaimi
  • 541
  • 6
  • 24
Irvin Chan
  • 2,217
  • 2
  • 14
  • 20
48

Actually, setting fetchPolicy to network-only still saves the response to the cache for later use, bypassing the reading and forcing a network request.

If you really want to disable the cache, read and write, use no-cache. Which is "similar to network-only, except the query's result is not stored in the cache."

Take a look at the official docs: https://www.apollographql.com/docs/react/data/queries/#configuring-fetch-logic

Bruno Peres
  • 2,583
  • 1
  • 19
  • 18
duske
  • 654
  • 6
  • 7
33

I would always suggest not to disable inbuild caching feature from apollo client. Instead you can always set fetchPolicy: 'network-only' for an individual queries. Something like this

<Query
    query={GET_DOG_PHOTO}
    variables={{ breed }}
    fetchPolicy='network-only'
>
 {({ loading, error, data, refetch, networkStatus }) => {
   ...
 }}
</Query>

While fetching data with this Query, it would always do a network request instead of reading from cache first.

Anuj
  • 851
  • 8
  • 19
  • 6
    Could it be possible to know why it is not recommended to disable Apollo client's cache? – Strider Oct 25 '19 at 21:10
  • 3
    solution I was working on in some edge cases with "fetchPolicy: 'network-only'" was still storing data in cache, and in concurrent cases was not showing the latest data, which was not what users wanted. It depends on the case, but my personal recommendation is 'no-cache' if you want to display the latest state from server all the time. It could be set per individual request or per whole client. – domingo Mar 01 '20 at 23:03
  • Sometimes its usefull to reset apollo cache: const client = useApolloClient(); someHandler =()=>{ client.resetStore(); } – northernwind Aug 02 '21 at 09:29