adi adi - 4 years ago 201
React JSX Question

Iterate loop over state object with an array key in React

I have a function

returning an object like:

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

Here's my React component calling the above function i.e.

class foo extends Component {

state = {
bar: {}
bar : getBar()
render() {
{, 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
but didn't get successful results.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download