1

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?

1
  • Current answers have some good ideas. Please post the code where you're actually using the data so we can be sure. You of course will want to make sure the data is being returned from your API successfully to begin with as well. Commented Oct 3, 2019 at 13:23

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

I think the problem is moreso in trying to access it than simply destructuring it. From what I understand, the destructuring he's doing could work successfully, but I'm not 100% certain.
De-structuring is a form of access. If the nested property doesn't exist, de-structuring an object will throw an error, the exact error he posted.
I'm able to destructure data before it's returned using the useQuery hook, however I do receive an error by trying to use it before it's loaded. Maybe it works differently in a Query component. I admit it may not be the best idea, and I need to placate TypeScript to do so, but, for example, this works: const { loading, error, data: {findAll}} = useQuery<any>(GET_FILERS);. Nothing built-in to JS throws an error.
3

Do you check if data has loaded yet?

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.