I'm trying to fetch from my backend database (MongoDB) on my localhost to display all blogposts.
I'm assuming I need to iterate through each blogpost on the frontend. Right now, only "Author" and "Comments" display, but with no actual data.
What would that syntax look like?
Here's what the React page looks like where I'm fetching and displaying.
import React, { Component } from 'react'
class Blog extends Component {
constructor() {
super()
this.state = {
blogPost: [],
finishedLoading: true
}
}
async componentDidMount() {
const response = await fetch('http://localhost:8000/api/blogPosts/all')
const json = await response.json()
this.setState({ blogPost: json.blogPosts, finishedLoading: false })
}
reload = async () => {
const response = await fetch('http://localhost:8000/api/blogPosts/all')
const json = await response.json()
this.setState({ blogPost: json.blogPosts, finishedLoading: true })
}
render() {
if (this.state.blogPost.length === 0) {
return (
<div className="App">
<h1>No blogposts have been posted!</h1>
</div>
)
}
return (
<div class="blogPost">
<h2>{this.state.blogPost.title}</h2>
<p> Author: {this.state.blogPost.author}</p>
<p>{this.state.blogPost.content}</p>
<p>Comments:</p>
<ul>
</ul>
</div>
)
}
}
export default Blog