Hammad Khalid
Hammad Khalid

Reputation: 548

GraphQL with React-Apollo: Cannot read property of undefined

I have the following gQL defined,

import gql from 'graphql-tag'

const SIGN_UP_QUERY = gql`
  query {
    signUpForm @client {
      firstName
      email
      password
    }
  }
`

and i use it with react-apollo query as such


<Query query={SIGN_UP_QUERY}>
    {({
      data: {
        signUpForm: { firstName }
      },
      loading
    }) => { ...... }}
</Query>

With this i am getting an error Cannot read property 'firstName' of undefined

What is it that i am doing wrong here?

Upvotes: 1

Views: 12827

Answers (3)

Long Nguyen Duc
Long Nguyen Duc

Reputation: 1325

Since you are destructuring variables, you need to make sure that data, also data.signUpForm are null OR undefined.

Here is an example for your situation.

There are three problems can make data/data.signUpForm is not an object:

  1. While loading the query, the data is undefined
  2. After loading, the signUpForm is not available in the apollo cache
  3. After loading, the signUpForm is available in the cache, but it's null

To resolve your problem:

  1. Process data after loading and query is not returned any error
  2. Make sure your data is available on the cache
  3. Make sure your returned data have a correct structure

Upvotes: 1

Calvin
Calvin

Reputation: 8775

You're de-structuring the data variable before it exists/has loaded. You should wait until loading = false before trying to access the data.

Upvotes: 6

Terje Laugaland
Terje Laugaland

Reputation: 196

Do you check if data has loaded yet?

if (loading) return "data not fetched yet";
return <p>{ firstName }</p>;

Upvotes: 3

Related Questions