gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:26:11 25 4
gpt4 key购买 nike

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?

最佳答案

是的,您可以使用 localStorage 来保存 Apollo 客户端缓存。 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

关于reactjs - 如何将localStorage与apollo-client和reactjs一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59211666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com