1

I have a function getBar() returning an object like:

{
  foo: 'value',
  array: ['a', 'b', 'c']
}

Here's my React component calling the above function i.e. getBar():

class foo extends Component {

  state = {
    bar: {}
  };    
  componentDidMount(){
    this.setState({
      bar : getBar()
    });
  }
  render() {
    {this.state.bar.array.map((value, i) => <div class="row" key={i}>{value}</div>)}
  }
}

It always gives me Uncaught TypeError: Cannot read property 'map' of undefined error. Exploring similar questions, I came to know I will have to declare an empty state array which I did in different ways but none worked. Can anybody please give me an appropriate answer preferably with complete logic.

I tried another way of declaring the state array to a const in render() but didn't get successful results.

1 Answer 1

2

Ok, so this is actually something to do with your component's lifecycle

The problem is that your render method runs before the componentDidMount method. So the first time your component renders your state looks like this:

{
  bar: {},
}

So no array property on bar, which means you cannot map over it (which is why you get errors 😣). Instead you could use the componentWillMount method, to set the state before the render method runs, or you could do a check on array being set before mapping over it.

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

1 Comment

Thanks a lot!! I was trying different tweaks since an hour but using componentWillMount worked flawlessly.

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.