I am trying to use Apollo client-state data with the hooks useQuery
and useMutation
as a global store inside a NextJS app.
When I follow the example from NextJS called with-apollo
(https://github.com/zeit/next.js/tree/canary/examples/with-apollo), which uses a HOC in which it runs all the queries and renders the app on the server first.
Normally, you want to catch the 'loading' state in a component like this:
const { loading, data } = useQuery(GET_NAME_QUERY) // some @client query
if (loading) return <p>Loading...</p>
return <h1>Hello {data.name</h1>
But I want to skip the loading-check and always have a default state available. I think this could be done with setting the cache of the apollo-client to a set of default values, like this:
const cache = new InMemoryCache().restore(initialState);
// This is the part where the initial client-state data is set:
cache.writeData({
data: { name: 'Harry' }
});
const apolloClient = new ApolloClient({
cache, // <-- cache with preset client-state data
typeDefs,
resolvers,
})
With the goal to just do this:
const { data } = useQuery(GET_NAME_QUERY) // some @client query, resolves immediately from cache
return <h1>Hello {data.name</h1>
I created a repo with a robot and its name & status that are cached from the beginning this way. See https://github.com/rnacken/next-with-apollo-client-state-cache
The client works, without any errors, but during SSR, I get an error, since it does not have the data yet (and 'loading' is true) after a useQuery
call.
When I log the loading/data state, I see this on the server:
On the client, it's all good:
Does anybody know how this is happening? With the cache set, I shouldn't see a loading:true state ever right? Is the getDataFromTree
from @apollo/react-ssr
not working correctly?