i am facing this problem right now on my react web-app. I try to map the students data from the laravel API that i created. Suddenly the web-app show this error to me Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'map')
Below is my code
state = {
students: [],
loading: true,
}
async componentDidMount() {
const res = await axios.get('http://localhost:8000/api/students');
/* console.log(res); */
if(res.data.status === 200){
this.setState({
students: res.data.students,
loading: false,
});
}
}
render(){
var student_HTMLTABLE = "";
if(this.state.loading){
student_HTMLTABLE =
<tr>
<td colSpan="7">
<h2>Loaidng ...</h2>
</td>
</tr>
}
else{
student_HTMLTABLE =
this.state.students.map( (item) => {
return(
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.course}</td>
<td>{item.email}</td>
<td>{item.phone}</td>
<td><Link to={`/edit-students/${item.id}`} className="btn btn-warning btn-sm">Edit</Link></td>
<td><Link to={`/delete-students/${item.id}`} className="btn btn-danger">Delete</Link></td>
</tr>
);
});
}
Please help me on how to solve this problem, almost 1 hour googling and still stuck :(
CodePudding user response:
This error is because your value is null and you're not checking null. Try this code
// null check
{
this.state.students && this.state.students.map((student , idx)=>{
// do some thing
})
}
CodePudding user response:
Just change it to students: res.data.students ?? [],
This will fix your problem in case students or data is empty.