问题描述
我正在尝试使用 Apollo Client 实现 Gatsby
export const wrapPageElement = ({ element,props }) => {
const client = new ApolloClient({
uri: "http://localhost:3000/graphql",cache: new InMemoryCache(),credentials: "include",});
window.a = client;
return (
<CookiesProvider>
<ApolloProvider client={client}>
<ChakraProvider theme={theme} {...props}>
{element}
</ChakraProvider>
</ApolloProvider>
</CookiesProvider>
);
};
我将登录的用户详细信息保存在 GraphQL 缓存中,以便可以在我的应用程序中的任何位置访问它。这是登录代码
const [login,{ data,error }] = useMutation(AUTH_USER,{
onCompleted: ({ login: data }) => {
try {
client.writeFragment({
id: "me",fragment: FRAGMENTS_USER.all_details,data: data,});
setToken(data.token);
} catch (e) {}
},});
我的问题是导航时正在重置缓存。因此,使用 gatsby-link 或 gatsby-navigation 正在重置我的缓存
我一直在使用 NextJS,这是我第一次在 Gatsby 中编写应用程序,但在这种情况下它似乎不像单页应用程序。
解决方法
wrapPageElement
和 wrapRootElement
API 需要在 gatsby-browser.js
和 gatsby-ssr.js
之间使用。两个文件需要共享相同的内容以避免持久性错误。因此,在您的 gatsby-ssr.js
:
export const wrapPageElement = ({ element,props }) => {
const client = new ApolloClient({
uri: "http://localhost:3000/graphql",cache: new InMemoryCache(),credentials: "include",});
window.a = client;
return (
<CookiesProvider>
<ApolloProvider client={client}>
<ChakraProvider theme={theme} {...props}>
{element}
</ChakraProvider>
</ApolloProvider>
</CookiesProvider>
);
};
正如您在 Gatsby's docs 中看到的:
注意:Gatsby’s Browser API 中有一个等效的钩子。这是 建议同时使用这两个 API。例如用法,请查看 Using redux。
也许这可以解决您的问题。