Reputation: 83
I am trying to make a page that renders all of the posts that I have on a mongodb server with the code:
constructor(props) {
super(props);
this.state = {
posts: []
}
this.listPosts = this.listPosts.bind(this);
}
componentDidMount() {
showAllPosts().then(res => {
console.log(res)
this.setState({
posts: res
})
})
console.log(this.state)
}
listPosts() {
this.state.posts.map(post =>
<listPost data={post}/>)
}
render() {
return (
<div>
<h1> All Posts </h1>
<ul class="mad-list">
{this.listPosts}
</ul>
</div>
)
}
As you can see, I console.log() the state after it was set and outside of the function, but the second console.log shows an empty array, so I'm sure there is something wrong with the way I am setting the state with this. I read that you should create a variable outside the function called that or self and set it to this and use it for the .setState function, but I tried that and it still didn't work. I am pretty sure there being no posts is what's stopping my listPosts function from working.
Upvotes: 0
Views: 56
Reputation: 73
I think a better way to do this could be
render() {
const {posts} = this.state;
let listPosts = (
posts.map(post => <listPost data={post}/>)
);
return (
<div>
<h1> All Posts </h1>
<ul class="mad-list">
{listPosts}
</ul>
</div>
)
}
I would explain what I did here. So on the const {posts} line, I extracted posts from your state and stored it in a variable.
Also, I saved the map in a variable that you could use directly in your JSX code.
I called the variable I created in your JSX to render contents.
This way your function listPosts isn't needed anymore unless there is something you want to do other than looping through your result
Upvotes: 1