I'm using axios to get data from the server and storing it in the state. When I do state.map( post => {console.log(post)} )
, I do not see anything.
I'm using Express
, Mongoose
, NextJS
and Axios
.
I'm using axios
to get data from the server and storing it in this.state.posts
. When I do console.log(this.state.posts)
in componentDidMount
, it logs the posts array perfectly. But when I do the same in
render(){ return ( /*here*/)}
it does not show anything.
This logs all the posts without an error
async componentDidMount() {
const { data } = await axios.get('/api/all')
this.setState({posts: data, isLoading: false})
console.log(this.state.posts)
}
But this does not log anything -
render() {
return({
posts.map( post => {
<Post title={post.title} />
})
})
}
{
posts.map( post => {
return <Post title={post.title} />
})
}
Maybe it works.
You can provide callback to setState
method which will run after the state is updated. You can use
this.setState({posts: data, isLoading: false}, () => console.log(this.state.posts))
to log updated state.
And in render method you should use
render() {
return(
this.state.posts.map( (post,i) => (
<Post title={post.title} key={i} />
))
)
}
or
render() {
const { posts} = this.state;
return(
<React.Fragment>
posts.map( (post,i) => (
<Post title={post.title} key={i} />
))
</React.Fragment>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With