Skip to content

Instantly share code, notes, and snippets.

@dksheffield
Created May 20, 2024 20:25
Show Gist options
  • Save dksheffield/0b4f05c66b9ec99f0039fc858cfdbd8a to your computer and use it in GitHub Desktop.
Save dksheffield/0b4f05c66b9ec99f0039fc858cfdbd8a to your computer and use it in GitHub Desktop.
Apollo Persistent Cache Options
import React from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { persistCache, AsyncStorageWrapper } from 'apollo3-cache-persist';
// Create an HTTP link to the GraphQL server
const httpLink = createHttpLink({
uri: 'https://your-graphql-endpoint.com/graphql',
});
// Optionally, set up authentication or other headers
const authLink = setContext((_, { headers }) => {
const token = AsyncStorage.getItem('auth-token');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
};
});
// Initialize the Apollo Client cache
const cache = new InMemoryCache();
// Persist the cache
(async () => {
await persistCache({
cache,
storage: new AsyncStorageWrapper(AsyncStorage),
});
})();
// Create the Apollo Client
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache,
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'all',
},
},
});
// Wrap your application in the ApolloProvider
const App = () => (
<ApolloProvider client={client}>
{/* Your app components go here */}
</ApolloProvider>
);
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment