Reputation: 69
I am making a post request and setting the state on a object on the response received. I need the data to be used so that I can map it and display it on a dropdown.
Tried using length
and did not work.
State in the component:
this.state = {
assignees: []
};
The API request:
axios
.post("http://localhost:3600/get_assignees", {
id: id
})
.then(res => {
this.setState({ assginees: res.data });
});
Destructuring:
const { assginees } = this.state;
Mapped on a select element throws Cannot read property length of undefined
<select className="Dropdown"
name="assginees"
defaultValue={"DEFAULT"} > {
assginees.length
? assginees.map(item => (
<option value={item} key={item}>
{item.login}
</option>
))
: null }
</select>
The response structure is similar to the one received here
GET /repos/:owner/:repo/collaborators
This is does to get the number of assignees available.
The state should be set when the data is received and I should be able to map it in the select option.
Upvotes: 0
Views: 61
Reputation: 20755
Problem is here
const { assginees } = this.state;
you have state assignees
and not assginees
a typo here,
just change it to this,
const { assignees } = this.state;
{assignees.length > 0
? assignees.map(item => (
<option value={item} key={item}>
{item.login}
</option>
))
: null}
Upvotes: 2