GraphQL playground returns data, while app returns null

Viewed 547

I am working on an app in React+TS/GraphQL/Prisma. The API is written in GraphQL and when I run a particular query in the playground, I get the data I expect, but when I run the exact same query in react, I get null. Why would this be?

What I run in query (relevant portion)

query {
  session {
    userData: {
      firstName
      lastName
      dateOfBirth 
    }
  }
}

and in the playground it returns

{
  "data": {
    "session": {
      "userData": {
        "firstName":"John",
        "lastName":"Doe",
        "dateOfBirth":null,
      }
    }
  }
}

but in the App, when I console log the userData or data.session it returns null for the whole object. console.log(data) prints

session: {
  userData: null
}

does anyone have any ideas why this would be? The playground accurately pulls user data and populates the subfields, but on the App in the browser, it only returns "null".

1 Answers

I discovered the solution and wanted to share it here.

The problem came because we are working on a session with data that updates. So user creates a session, then updates, then the next step updates some more, etc before finally submitting the session.

The problem described in my question is based on Apollo defaulting to cache-first as it's fetch policy. So when the user updates, the next step queries the non-updated, cached version of the session data.

To fix this, at each step in the process, we need to call our query and set the fetch policy to "network-only" like so:

const {loading, error, data} = useSessionQuery({fetchPolicy: 'network-only'});

This will ensure that data is pulled from the network where your updateMutation was performed instead of the cached (outdated) copy.

Related