How to use map() with data from axios response?
Solution 1
{
posts.map( post => {
return <Post title={post.title} />
})
}
Maybe it works.
Solution 2
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>
)
}
Solution 3
Can you try this:
async componentDidMount() {
const { data } = await axios.get('/api/all')
this.setState({posts: data, isLoading: false}, () => {
console.log(this.state.posts)
return;
})
}
Solution 4
You need to return direclty posts.map
with out opening {}
render() {
const { posts = [] } = this.state
return(
posts.map( post =>
<Post title={post.title} />
)
)
}
const { posts = [] }
will make sure that posts
is an array and don't give you any errors like cannot read .map of undefined
Or you can open {}
inside a React.Fragment
render() {
const { posts = [] } = this.state
return(
<>
{
posts.map( post =>
<Post title={post.title} />
)
}
</>
)
}
Solution 5
Modify your render method like this:
render() {
let Posts = {...this.state.posts};
return({
Posts.map( post => <Post title={post.title} />);
})
}
Your code is not correctly referencing the posts in state. Also,this way any operation on posts will not affect the state object directly. Hope this helps!
Ajay Yadav
Updated on June 17, 2022Comments
-
Ajay Yadav almost 2 years
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
andAxios
.I'm using
axios
to get data from the server and storing it inthis.state.posts
. When I doconsole.log(this.state.posts)
incomponentDidMount
, it logs the posts array perfectly. But when I do the same inrender(){ 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} /> }) }) }
-
Ajay Yadav almost 5 yearsThanks a lot!!! This single word had been haunting me since all day. But only to fix this error, I learned a lot of things today!
-
Ajay Yadav almost 5 yearsI already tried it thinking its a problem about callbacks ! but the problem is fixed now and it was a silly mistake I wasn't returning the <Post /> in map()
-
Masoud Rahimi almost 5 yearsFor a better answer try to add some explanation to your code.