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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With