Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use map() with data from axios response?

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} />
    })  
  })
}
like image 834
Ajay Yadav Avatar asked Jun 11 '19 11:06

Ajay Yadav


2 Answers

{ 
   posts.map( post => {
    return <Post title={post.title} />
}) 
}

Maybe it works.

like image 94
xiaoshuaicao Avatar answered Oct 25 '22 21:10

xiaoshuaicao


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>
   )
 }
like image 38
Sahil Raj Thapa Avatar answered Oct 25 '22 21:10

Sahil Raj Thapa