8

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} />
    })  
  })
}
1
  • Try to wrap your jsx code with <React.Fragment> Commented Jun 11, 2019 at 11:38

7 Answers 7

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

Maybe it works.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks 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!
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>
   )
 }

Comments

1

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;
    })    
  }

1 Comment

I 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()
1

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} />
        )
      }
    </>    
  )
}

Comments

1

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!

Comments

0
async componentDidMount(){

const res = await axios.get('/api/all')
  this.setState({
  post: res.data
  })
}

1 Comment

For a better answer try to add some explanation to your code.
-1
export default class Blog extends Component {
state = {post:[]}
componentDidMount() {
            // Make a request for a user with a given ID
axios.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
    this.setState({post:response.data})
  // handle success
})
.catch(function (error) {
  // handle error
  console.log(error);
})
.then(function () {
  // always executed
});
}render(){
const posts = this.state.post;
 const allposts = posts.map(post =>{
return( 
       <div>{post.title}</div>
 )
});
return(
<div>{allposts}</div>
);
}}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.