React throws undefined error for an existing element

Viewed 153

I'm trying to walk through an array and use its data but it was returning the error:

TypeError: Cannot read property 'forEach' of undefined

This is the result of the log:

class Restockers extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
       ...
    }
  }

  render() {
    const rows = [];
    console.log('props: ', this.props); // this logs the content of props
    this.props.restockers.restockers.forEach(...)

  }
}

So when there is this.props.restockers.restockers in the code, in the log it is only this.props.restockers, which has an empty array.

Like in the next screenshot:

enter image description here

So I remove that extra restockers from the code. And now look at my error and my log:

enter image description here

I don't understand this weird behavior, now in the log it is this.props.restockers.restockers so the code is wrong because it is this.props.restokers.

How can this be solved?

1 Answers

You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So better use map because it returns an array like this.

render() {
    const rows = [];
    console.log('props: ', this.props); // this logs the content of props
    this.props.restockers.restockers.map((restocker, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Restockerkey={i} restocker={restocker} />) 
        })

  }
Related