Reputation: 22361
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.
Upvotes: 1
Views: 1824
Reputation: 6253
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.
Upvotes: 2