I have a react app with apollo client. When a user logs in, I can query the client state and retrieve the user however, when I refresh the page, the user data is no longer set.
As you can see, I have my index.js
file where I set the client and then pass that to my ApolloProvider
which wraps my entire application.
// 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")
)
I should add that when I log window.localStorage
after refreshing the page, I can see my logged in user
object. When I query the user after refreshing the page, I only get the defaults that are set in clientState defaults.
Also, I know the GET_USER
query works because after logging in and writing the user object the the cache, the GET_USER
query runs and the user object is returned.
For reference, my GET_USER
query is as so:
gql`
{
user @client {
username
salesChannel
fullName
isLoggedIn
}
}
`
Why does the user object not persist in the cache after reloading the page?
Apparently changes to the InMemoryCache
cache made with writeQuery
and writeFragment
disappears after reloading the page.
Apollo Client docs:
If you reload your environment then changes made with writeQuery and writeFragment will disappear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With