如何将本地存储与apollo-client和reactjs一起使用?

时间:2019-12-06 10:49:11

标签: reactjs local-storage react-apollo apollo-client

  

我需要使用reactjs和apollo-client为在线商店制作购物车。   如何使用apollo-client和localStorage持久存储数据?

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

这是一个有效的示例,显示了如何使用Apollo GraphQL client管理本地状态以及如何使用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:

enter image description here

答案 2 :(得分:0)

我知道我来晚了,但是我找到了一种使用最新版本处理此问题的完美方法: 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,这将帮助您快速设置。