8

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?

Yuci
  • 27,235
  • 10
  • 114
  • 113
user246328
  • 103
  • 1
  • 1
  • 6
  • local storage will work only on client side. If you are looking for persisting values even after session then you have to send it to server – Mukund Dec 06 '19 at 11:07
  • Can I save data to localStorage with help apollo client? – user246328 Dec 06 '19 at 11:13
  • yes you can use apollo-cache-persist to persist the cache. you can check the e.g given at https://github.com/apollographql/apollo-cache-persist – Mukund Dec 06 '19 at 11:36
  • Suggestion: Either you can use contextAPI https://reactjs.org/docs/context.html or a redux store. – Kriti Dec 11 '19 at 14:42

3 Answers3

17

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

Yuci
  • 27,235
  • 10
  • 114
  • 113
2

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,
  ...
});
abdelhedi hlel
  • 2,903
  • 1
  • 16
  • 20
1

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
briancoder
  • 159
  • 1
  • 9