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.
JavaScript
x
45
45
1
componentDidMount() {
2
console.log("component did mount");
3
axios.get('http://localhost:3000/')
4
.then(response => {
5
if (response.data.length > 0) {
6
this.setState({
7
blogs: response.data
8
});
9
}
10
})
11
.catch((error) => {
12
console.log(error);
13
})
14
15
}
16
17
render(){
18
console.log("inside render ");
19
20
var b=this.state.blogs.map((blog)=>{
21
console.log(blog);
22
var taggu=blog.tag.map((tag)=>{
23
return(
24
<span>{tag}</span>
25
)
26
});
27
var con=blog.content.slice(0,100);
28
return(
29
<Col className="my-1" lg="4" sm="6" >
30
<Card key={blog._id}>
31
<CardHeader tag="h3">{blog.topic}</CardHeader>
32
<CardBody>
33
<CardTitle tag="h5">By {blog.writer.username}</CardTitle>
34
<CardText>{con} </CardText>
35
<Button>Learn More</Button>
36
</CardBody>
37
<CardFooter>{taggu}</CardFooter>
38
</Card>
39
</Col>
40
)
41
});
42
43
44
return ( <div className="App">{b}</div>)
45
}
Advertisement
Answer
The Promise
from axios
does not resolve
instantly and it is very likely that the render
function was called before
JavaScript
1
4
1
this.setState({
2
blogs: response.data
3
});
4
was executed, meaning that this.state.blogs
is undefined.
You could either add
JavaScript
1
4
1
this.setState({
2
blogs: []
3
});
4
in the constructor or check whether this.state.blogs
is undefined before calling its map function:
JavaScript
1
6
1
render(){
2
console.log("inside render ");
3
if(!this.state.blogs)
4
return <span>Loading</span>;
5
// Rest of the code below...
6