I was using axios to GET an array of usernames and use setState to update the state. I have log the users to console to ensure that it is an array.
axios.get("http://localhost:5000/users/")
.then((res) => {
if (res.data.length > 1) {
const users = res.data.map(el => el.username);
setState((preValue) => {
return {
...preValue,
users : users
}
})
console.log(state)
}
})
.catch((err)=>console.log(err))
When it get rendered out in JSX. The map method of the array returns an undefined error. However, the array can be rendered out as a string.
<h3>Edit Exercise</h3>
<form onSubmit={onSubmit}>
<div className="form-group">
<label>Username: {state.users}</label>
{/* <select required className="form-control"
value={state.username} onChange={onChangeUsername}>
{
state.users.map(function (user) {
return <option key={user} value={user}>{user}</option>
})
}
</select> */}
</div>


res.data.length > 1condition is not satisfied then thestatewill not get updated. In order to avoid that you can initialse the state likethis.state = { users: [] }. Also while rendering you can use(state.users || []).maporstate.users?.mapin order to avoid the crash.