getting error (Cannot read properties of undefined (reading 'map')) while rendering list. the code is attached below please help. REACT Code in which Data have been fetched and tried rendered.
import React, { Component } from 'react'
// import axios from 'axios';
export default class List extends Component {
constructor(props)
{
super(props);
this.state={apiResponse:[]};
}
callAPI()
{
fetch("http://localhost:9000/testAPI")
.then( (res) => res.json())
.then( (data) => {this.setState({apiResponse: data.task});});
}
componentWillMount()
{
this.callAPI();
}
render() {
return (
<div>
<h1>{this.state.apiResponse}</h1>
{
this.state.apiResponse.map((r)=>
<li >r.task</li>
)
}
</div>
)
}
}
NODE JS from where the data is being fetched to react
router.get("/",function(req,res)
{
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("to-do");
// var query = { address: "Park Lane 38" };
dbo.collection("to-do").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
res.json(result)
// res.send((result))
db.close();
});
});
})
Your problem is that your json response is not including the task-property (at least not every time). By setting apiResponse to this value you are setting it to undefined and the map-function is not available anymore. A workaround could be to check if the property task is available before setting the state.
fetch("http://localhost:9000/testAPI")
.then( (res) => res.json())
.then( (data) => {
if (data.task) {
this.setState({apiResponse: data.task});
}
});