I am kind of new to React. And I got this Error: Objects are not valid as a React child (found: [object Promise]). And I am not sure how to fix this issue. Can you guys take a look? Thanks!
Here's my code.
import React, { Component } from "react";
import "./App.css";
async function randomVerse() {
const url = "https://labs.bible.org/api/?passage=random&type=json";
const passage = await fetch(url);
const passageJson = await passage.json();
return passageJson;
}
const displayRandomVerse = async () => {
let result = await randomVerse();
let verse = "";
verse += result[0].text;
return verse;
};
const returnVerse = displayRandomVerse();
class App extends Component {
constructor() {
super();
this.state = {
verse: null
};
}
componentDidMount() {
this.setState({verse: returnVerse});
};
render() {
return (
<div className="App">
<h1>Good Morning, XXX!</h1>
<h3>Bible verse : {this.state.verse} </h3>
</div>
);
}
}
export default App;
You have to set await in const returnVerse = await displayRandomVerse();. This should give you the value
You need to fetch and await in your componentDidMount method
async function randomVerse() {
const url = "https://labs.bible.org/api/?passage=random&type=json";
const passage = await fetch(url);
const passageJson = await passage.json();
return passageJson;
}
const displayRandomVerse = async () => {
let result = await randomVerse();
let verse = "";
verse += result[0].text;
return verse;
};
class App extends Component {
constructor() {
super();
this.state = {
verse: null
};
}
async componentDidMount() { //Notice changes in this section
this.setState({verse: await displayRandomVerse()});
};
render() {
return (
<div className="App">
<h1>Good Morning, XXX!</h1>
<h3>Bible verse : {this.state.verse} </h3>
</div>
);
}
}
export default App;