Str*_*ch0 6 apollo reactjs graphql react-apollo apollo-client
我有一个与阿波罗客户端的应用程序。当用户登录时,我可以查询客户端状态并检索用户,但是,当我刷新页面时,不再设置用户数据。
如您所见,我在我的index.js文件中设置了客户端,然后将其传递给ApolloProvider包装了整个应用程序的文件。
// index.js
const client = () => {
const cache = new InMemoryCache()
persistCache({
cache,
storage: window.localStorage
})
return new ApolloClient({
uri: graphQLUri,
credentials: 'include',
clientState: {
defaults: {
locale: "en-GB",
user: {
__typename: "User",
isLoggedIn: false,
username: "",
salesChannel: "",
fullName: ""
}
},
typeDefs: `
enum Locale {
en-GB
fr-FR
nl-NL
}
type Query {
locale: Locale
}
`
},
cache
})
}
ReactDOM.render(
<ApolloProvider client={client()}>
<App />
</ApolloProvider>,
document.getElementById("root")
)
Run Code Online (Sandbox Code Playgroud)
我应该补充一点,window.localStorage刷新页面后登录时,我可以看到登录user对象。在刷新页面后查询用户时,我仅获得在clientState默认值中设置的默认值。
另外,我知道GET_USER查询有效,因为在登录并写入用户对象缓存后,GET_USER查询就会运行并返回用户对象。
供参考,我的GET_USER查询是这样的:
gql`
{
user @client {
username
salesChannel
fullName
isLoggedIn
}
}
`
Run Code Online (Sandbox Code Playgroud)
重新加载页面后,为什么用户对象不保留在缓存中?
InMemoryCache显然,对缓存所做的更改在重新加载页面后就会writeQuery消失。writeFragment
如果重新加载环境,则使用 writeQuery 和 writeFragment 所做的更改将消失。