I have tried many solutions given on StackOverflow as well as on other platforms but nothing worked. I am new to ReactJs and I am unable to understand what is wrong in this code that I am getting this error.
componentDidMount() { console.log("component did mount"); axios.get('http://localhost:3000/') .then(response => { if (response.data.length > 0) { this.setState({ blogs: response.data }); } }) .catch((error) => { console.log(error); }) } render(){ console.log("inside render "); var b=this.state.blogs.map((blog)=>{ console.log(blog); var taggu=blog.tag.map((tag)=>{ return( <span>{tag}</span> ) }); var con=blog.content.slice(0,100); return( <Col className="my-1" lg="4" sm="6" > <Card key={blog._id}> <CardHeader tag="h3">{blog.topic}</CardHeader> <CardBody> <CardTitle tag="h5">By {blog.writer.username}</CardTitle> <CardText>{con}... </CardText> <Button>Learn More</Button> </CardBody> <CardFooter>{taggu}</CardFooter> </Card> </Col> ) }); return ( <div className="App">{b}</div>)
}
Advertisement
Answer
The Promise
from axios
does not resolve
instantly and it is very likely that the render
function was called before
this.setState({ blogs: response.data });
was executed, meaning that this.state.blogs
is undefined.
You could either add
this.setState({ blogs: [] });
in the constructor or check whether this.state.blogs
is undefined before calling its map function:
render(){ console.log("inside render "); if(!this.state.blogs) return <span>Loading...</span>; // Rest of the code below...