kadddeee
kadddeee

Reputation: 498

Why the TypeError: Cannot read property '0' of undefined?

I am pulling data from woocommerce.

Which I have defined as so in my render(): const product2 = this.state.products2;

Now I want to target a particular value in this returned object as such: const defaultLace = product2.default_attributes[0].option

However, the above renders a Type Error but const defaultLace = product.default_attributes; does not render an error and in the console I can see the data similar in this way;

      default_attributes: [
        {
          id: 0,
          name: "Lace",
          option: "Closure"
        }
      ]

What is happening here that this const defaultLace = product2.default_attributes[0].option renders an error?

Any help?

---EDIT----

broken code replication: XXXX

Upvotes: 3

Views: 84

Answers (2)

Tholle
Tholle

Reputation: 112917

products2 is initially an empty array before the request has finished, so accessing products2.default_attributes will give undefined, and trying to access [0] on that will give rise to your error.

You could wait with the rendering until the products2 array has been filled with data.

Example

render() {
  const product2 = this.state.products2;

  if (product2.length === 0) {
    return null;
  }

  const productSize = product2[0].default_attributes[0].option;

  return (
    <div>
      <h1>{productSize}</h1>
    </div>
  );
}

Upvotes: 1

Aleš Dost&#225;l
Aleš Dost&#225;l

Reputation: 152

This code is OK.

But when you retrive data from remote server you must check that data exist and are in your structure.

When you use

const defaultLace = product2.default_attributes[0].option

you must check data as:

if(product2 && product2.default_attributes && Array.isArray(product2.default_attributes) && product2.default_attributes.length > 0) {
    const defaultLace = product2.default_attributes[0].option
} else {
   throw new Error('Bad data');
}

Upvotes: 1

Related Questions