使用Apollo Client 3.0 Beta并尝试集成缓存持久性。
我得到的错误是
未捕获(承诺)错误:网络错误:在以下位置找不到字段用户 ROOT_QUERY对象
而且,确实如此,我的缓存(在Apollo Dev Tools下)完全是空的。 我不知道为什么。我试图对缓存持久性进行建模,使其与文档中的示例非常接近。
有趣的是,我的console.log(带有查询结果)都没有被调用。 在尝试集成缓存持久性之前,登录和注册工作正常。但是显然,我希望人们能够刷新页面并仍然可以登录。有什么主意我在做错什么吗?
import React, { Fragment, useState, useEffect } from "react";
import { Modal } from "@redq/reuse-modal";
import { ApolloProvider } from "@apollo/client";
import "@redq/reuse-modal/es/index.css";
import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
import { resolvers, typeDefs } from "../Resolvers";
import { setContext } from "@apollo/link-context";
import { persistCache } from "apollo-cache-persist-dev";
import fetch from "node-fetch";
import { IS_CURRENTLY_LOGGED_IN } from "../MutationsQueries";
export default ({ Component, pageProps }) => {
const [client, setClient] = useState(undefined);
useEffect(() => {
const cache = new InMemoryCache();
const dev = "http://localhost:3001/";
const prod = "https://xxxxxx.now.sh/";
const httpLink = createHttpLink({
uri: dev,
onError: ({ networkError, graphQLErrors }) => {
console.log("graphQLErrors", graphQLErrors);
console.log("networkError", networkError);
},
credentials: "include",
fetch
});
const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
const user = client.readQuery({
query: IS_CURRENTLY_LOGGED_IN
});
const token = localStorage.getItem("token");
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${user.token}` : ""
}
};
});
const client = new ApolloClient({
ssrMode: true,
disableOffline: true,
link: authLink.concat(httpLink),
cache,
typeDefs,
resolvers
});
const data = {
isLoggedIn: false,
currentlyLoggedIn: [],
networkStatus: {
__typename: "NetworkStatus",
isConnected: false
}
};
cache.writeData({ data });
persistCache({
cache,
debug: true,
storage: window.localStorage
}).then(() => {
client.onResetStore(async () => cache.writeData({ data }));
setClient(client);
});
return () => {
const user = client.readQuery({ query: IS_CURRENTLY_LOGGED_IN });
console.log(user);
};
}, []);
if (client === undefined) return <div>Loading...</div>;
return (
<ApolloProvider client={client}>
<Fragment>
<Modal />
<Component {...pageProps} />
</Fragment>
</ApolloProvider>
);
};
export const IS_CURRENTLY_LOGGED_IN = gql`
query isUserCurrentlyLoggedIn {
isLoggedIn @client
user @client {
name
user_id
email
token
isLoggedIn
}
}
`;