0

I'm trying to iterate over an array of Objects in React fetched from Django. My object is an array, but when I try to map it I get a typeerror: cannot read property map of undefined.

The state has structure:

Unit: { alliances: [{description: "", id: 6, name: "Elusive"}, {...}] icon_url id name }

which is what shows in React Developer tools as well. In another component I'm doing something very similar with a state that is a nested array of units with the same structure as the above, so I'm at a loss as to why this doesn't work.

class UnitInfo extends Component {
  state = {
    unit: []
  };

  // ...

  render() {
    return (
      <div>
        <h1>{this.state.unit.name}</h1>
        <img src={this.state.unit.icon_url} alt="{this.state.unit.name} icon" />
        {this.state.unit.alliances.map(alliance => (
          <div key={alliance.id}>
            <h4>{alliance.name}</h4>
          </div>
        ))}
      </div>
    );
  }
}
1
  • 2
    You are not initialising your state with a unit that contains alliances. Commented Jun 30, 2019 at 20:54

1 Answer 1

2

You are fetching the data from Django, meaning that initially the data doesn't exist. It only exists once the fetch is complete and the state has been updated.

As seen in your code example, your initial state is unit: [], which is why you cannot map over unit.alliances because unit is an empty array and does not have an alliances property.

You can safe-guard against this by adding a check in your render:

{this.state.unit.alliances && this.state.unit.alliances.map(alliance => (
  <div key={alliance.id}>
    <h4>{alliance.name}</h4>
  </div>
))}

That being said you should probably keep your state consistent and have unit be an empty object rather than an empty array. You could also have your state as unit: {alliances: []} and skip the safe-guard altogether.

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

1 Comment

Rather fix the initial state to have an empty alliances array. unit should never be an array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.