繁体   English   中英

如何在 apollo-client 和 reactjs 中使用 localStorage?

[英]How to use localStorage with apollo-client and reactjs?

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

是的,您可以使用 localStorage 来持久化 Apollo Client 缓存。 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();

你可以在我的 GitHub Repo上找到这个例子。

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

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

在此处输入图片说明

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

我知道我有点晚了,但我找到了一种使用最新版本处理此问题的完美方法: 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
    }));
    
});

如需更多信息,请阅读此处的文档,它将帮助您快速设置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM