Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use localStorage with apollo-client and reactjs?

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?

like image 477
user246328 Avatar asked Dec 06 '19 10:12

user246328


1 Answers

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:

enter image description here

like image 142
Yuci Avatar answered Nov 15 '22 08:11

Yuci