Search code examples
reactjsapolloapollo-clientreact-apollo

Apollo Client client.readQuery returning null when data is in the cache


This must be user error, but I've got an app with a simple currentUser query that looks at a JWT for an id, looks it up, and returns the appropriate user.

I can look at devtools and see that it's in the cache as __ref:User:19

export const CURRENT_USER_QUERY = gql`
  query{
    currentUser {
      id
      fullName
      email
    }
  }
`

But in my component, when I do const { currentUser } = client.readQuery({ query: CURRENT_USER_QUERY }); it (intermittently) blows up because:

Cannot destructure property 'currentUser' of 'client.readQuery(...)' as it is null.

User:19 exists and is all the stuff I need. I hit reload, and that same page works.

I have my default error policy set to "all" in the client.

This is version 3.3.11 of the client. Chrome v88.04, for what that's worth. React 17.01.

Am I missing something here? Should that not return a value synchronously (and dependably) if that item's in the cache?

Is there a better way to deal with that situation? I'm trying to move this app away from storing things in redux or some context provider since it's already being handled by Apollo. Seems redundant to have that responsibility handled by a bunch of different things.


Solution

  • I was facing the same issue. I fixed it like this:

    const existingData = cache.readQuery({
       query: GET_CONTRACT,
       variables: {
           ...variables, // fixed: passing the same reference to variables
       },
    });