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

8
我需要使用ReactJS和Apollo-Client为在线商店创建购物车。如何使用Apollo-Client和localStorage来持久化数据?

本地存储仅在客户端上工作。如果您想要在会话结束后持久化值,则必须将其发送到服务器。 - Mukund
我能否使用Apollo客户端将数据保存到localStorage中? - user246328
是的,您可以使用 apollo-cache-persist 来持久化缓存。您可以查看 https://github.com/apollographql/apollo-cache-persist 上提供的示例。 - Mukund
建议:您可以使用contextAPI https://reactjs.org/docs/context.html或redux存储。 - Kriti
3个回答

17

是的,你可以使用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仓库上找到此示例。

顺便说一下,应用程序的外观如下:

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

enter image description here


2

文档: 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

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

想了解更多信息,请阅读文档,这将帮助您快速设置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接