FIrman
FIrman

Reputation: 131

React native cannot read property '0' of undefine

I'm new with ReactJS and today I have encountered a few problems. I am currently using Redux to store my data and I was able to retrieve all the data from the props.

Ie.

const { recipe, loadingRDetail } = this.props;
console.log(recipe.macros); 

recipe macros will show me 5 values in array. Array Image Console Log

But when I tried to accessed to the array, It will throw me an error "Cannot read property '0' of undefined".

I have tried

console.log(recipe.macros[0])

and

const {macros} = recipe;
macros.map((i) => {
    ....
}...

I have no luck with both of these

This is the error I get Red Warning error

Upvotes: 1

Views: 293

Answers (1)

Mohamed Sadat
Mohamed Sadat

Reputation: 255

Actually, it's just because your macros data is asynchronously loaded so you have to add a test to check if it's loaded.

You can try this:

const {macros} = recipe;
if (macros && macros.length) {
  macros.map((i) => {
      ....
   }...
}

Or if you already are in your Render method you can just try this :

const {macros} = recipe;
return (
  {
    macros && macros.length && /* It will check if macros has elements inside */
      macros.map((i) => {
          ....
       }...
    }
  }
)

Upvotes: 1

Related Questions