How to use localStorage with apollo-client and reactjs?
Asked Answered
J

3

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?

Jacinthe answered 6/12, 2019 at 10:49 Comment(4)
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 serverVaccinia
Can I save data to localStorage with help apollo client?Jacinthe
yes you can use apollo-cache-persist to persist the cache. you can check the e.g given at github.com/apollographql/apollo-cache-persistVaccinia
Suggestion: Either you can use contextAPI reactjs.org/docs/context.html or a redux store.Reshape
I
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

Isom answered 16/12, 2019 at 15:51 Comment(0)
B
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,
  ...
});
Barksdale answered 11/12, 2019 at 11:9 Comment(0)
T
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.

Thorium answered 31/10, 2020 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.