如何禁用阿波罗链接或阿波罗客户端缓存?

我使用 Apollo 客户Apollo-Link反应,阿波罗,我想完全禁用缓存,但不知道如何做到这一点。

我读了 apollo-cache-inmemory的源代码,它的构造函数中有一个 config参数,但是我不能构建一个虚拟的 storeFactory来使它工作。

81493 次浏览

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

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

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.