I need to make a cart for an online shop using reactjs and apollo-client. How can I persist data using apollo-client with localStorage?
Yes, you can use localStorage to persist Apollo Client cache. apollo-cache-persist can be used for all Apollo Client 2.0 cache implementations, including InMemoryCache and Hermes.
Here is a working example, which shows how to use Apollo GraphQL client to manage the local state and how to use apollo-cache-persist to persist the cache in the localStorage.
import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { ApolloProvider } from '@apollo/react-hooks';
import { persistCache } from 'apollo-cache-persist';
import { typeDefs } from './graphql/schema';
import { resolvers } from './graphql/resolvers';
import { GET_SELECTED_COUNTRIES } from './graphql/queries';
import App from './components/App';
const httpLink = createHttpLink({
uri: 'https://countries.trevorblades.com'
});
const cache = new InMemoryCache();
const init = async () => {
await persistCache({
cache,
storage: window.localStorage
});
const client = new ApolloClient({
link: httpLink,
cache,
typeDefs,
resolvers
});
/* Initialize the local state if not yet */
try {
cache.readQuery({
query: GET_SELECTED_COUNTRIES
});
} catch (error) {
cache.writeData({
data: {
selectedCountries: []
}
});
}
const ApolloApp = () => (
<ApolloProvider client={client}>
<App />
</ApolloProvider>
);
ReactDOM.render(<ApolloApp />, document.getElementById('root'));
};
init();
You can find this example on my GitHub Repo.
By the way, the app looks like this:
And its localStorage looks like below in the Chrome DevTools:
Documentation : https://github.com/apollographql/apollo-cache-persist
import { InMemoryCache } from 'apollo-cache-inmemory';
import { persistCache } from 'apollo-cache-persist';
const cache = new InMemoryCache({...});
// await before instantiating ApolloClient, else queries might run before the cache is persisted
await persistCache({
cache,
storage: window.localStorage,
});
// Continue setting up Apollo as usual.
const client = new ApolloClient({
cache,
...
});
I know I'm a bit late but I found a perfect way of handling this with the latest version:apollo3-cache-persist
Heres my code:(Remember to import these modules)
const cache = new InMemoryCache();
const client = new ApolloClient({
//your settings here
});
const initData = {
//your initial state
}
client.writeData({
data: initData
});
//persistCache is asynchronous so it returns a promise which you have to resolve
persistCache({
cache,
storage: window.localStorage
}).then(() => {
client.onResetStore(async () => cache.writeData({
data: initData
}));
});
Fore more info please read the documentation here it will help you get set up quick.
© 2022 - 2024 — McMap. All rights reserved.