如何将 localStorage 与 apollo-client 和 reactjs 一起使用?

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?

文档: 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,
  ...
});

是的,您可以使用 localStorage 来保存 Apollo 客户端缓存。 apollo-cache-persist 可用于所有 Apollo Client 2.0 缓存实现,包括 InMemoryCache 和 Hermes。

这是一个工作示例,展示了如何使用 Apollo GraphQL 客户端 管理本地状态以及如何使用 apollo-cache-persist 将缓存持久保存在 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();

您可以在 my GitHub Repo 上找到此示例。

顺便说一句,该应用程序如下所示:

它的 localStorage 在 Chrome DevTools 中如下所示:

我知道我有点晚了,但我找到了用最新版本处理这个问题的完美方法:apollo3-cache-persist

这是我的代码:(记得导入这些模块)

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
    }));
    
});

有关详细信息,请阅读 documentation 此处,它将帮助您快速设置。