I'm working on a full-stack project using Express in back-end and react in front-end. Now the problem is with a specific component. It is supposed to fetch the results of a database query from /api/blogposts. But then it goes wrong.
here's my code:
import React from 'react';
import './Blogposts.css';
import SingleBpost from '../SingleBpost/SingleBpost.js';
class Blogposts extends React.Component {
constructor(props) {
super(props);
this.state = {
receivedPosts: []
};
}
async getBpostsFromServer() {
const response = await fetch("/api/blogposts");
let myPosts = await response.json();
this.setState({receivedPosts: myPosts});
}
componentDidMount() {
this.getBpostsFromServer();
}
render() {
console.log(this.state.receivedPosts);
return(
<div id="Blogposts">
<SingleBpost title="Test" date="18/12/2021" author="Kepos Team" body="Hello, this is a test for the blogposts!" />
</div>
);
}
}
export default Blogposts;
There is only one console.log: console.log(this.state.receivedPosts); but the console gives me two results: first it prints an array that I don't recognize, then it prints the array that I need. (here's a screenshot https://imgur.com/a/q40aVkq).
But when I try to feed the data from this.state.receivedPosts into my component like this:
<SingleBpost title={this.state.receivedPosts[0].title} (etc etc) />
It doesn't work (my screen sctually turns blank).
Does anyone have any idea as to what I'm doing wrong here? Thanks for any help!
You can use && which will protect you from that case
render() {
return (
this.state.receivedPosts && this.state.receivedPosts.length
<div id="Blogposts">
<SingleBpost title="Test" date="18/12/2021" author="Kepos Team" body="Hello, this is a test for the blogposts!" />
</div>
);
}
Or handling it via ternary operator:
render() {
return (
this.state.receivedPosts && this.state.receivedPosts.length ?
<div id="Blogposts">
<SingleBpost title="Test" date="18/12/2021" author="Kepos Team" body="Hello, this is a test for the blogposts!" />
</div> : null
);
}