How to disable cache in apollo-link or apollo-client?

React Apollo

React Apollo Problem Overview


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.

React Apollo Solutions


Solution 1 - React Apollo

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

Solution 2 - React Apollo

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

Solution 3 - React Apollo

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJacky LeeView Question on Stackoverflow
Solution 1 - React ApolloIrvin ChanView Answer on Stackoverflow
Solution 2 - React ApolloduskeView Answer on Stackoverflow
Solution 3 - React ApolloAnujView Answer on Stackoverflow