Objects are not valid as a React child (found: [object Promise])
I also received the same error message when creating an async functional component. Functional components should not be async.
const HelloApp = async (props) => { //<<== removing async here fixed the issue
return (
<div>
<h2>Hello World</h2>
</div>
)
}
ReactDOM.render(<HelloApp />, document.querySelector("#app"))
jsfiddle
Using React Hooks:
UPDATE 2020-08-01: Amended with @ajrussellaudio's suggestion.
import React, {useState, useEffect} from "react"
const ShowPosts = () => {
const [posts, setPosts] = useState([]);
useEffect( () => {
async function fetchData() {
try {
const res = await axios.get('/posts');
setPosts(res.data);
} catch (err) {
console.log(err);
}
}
fetchData();
}, []);
return <div>{posts}</div>
}
this.renderPosts()
will return a Promise
not the actual data, and AFAIK Reactjs will not resolve Promises implicitly in render
.
You need to do it like this
componentDidMount() {
this.renderPosts();
}
renderPosts = async() => {
try {
const res = await axios.get('/posts');
const posts = res.data;
// this will re render the view with new data
this.setState({
Posts: posts
});
} catch (err) {
console.log(err);
}
}
render() {
const posts = this.state.Posts?.map((post, i) => (
<li key={i} className="list-group-item">{post.text}</li>
));
return (
<div>
<ul className="list-group list-group-flush">
{posts}
</ul>
</div>
);
}