I am trying to render a list of posts by mapping through an array. I've done this many times before but for some reason
renderPosts = async () => { try { let res = await axios.get('/posts'); let posts = res.data; return posts.map((post, i) => { return ( <li key={i} className="list-group-item">{post.text}</li> ); }); } catch (err) { console.log(err); } } render () { return ( <div> <ul className="list-group list-group-flush"> {this.renderPosts()} </ul> </div> ); }
All I get is:
Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
I've checked the data returned from renderPosts and it is an array with the correct values and no promises. What's going on here?
The React. js error "Objects are not valid as a React child" occurs when we try to directly render an object or an array in our JSX code. To solve the error, use the map() method to render arrays or access properties on the object in your JSX code.
The "Objects are not valid as a React child" error happens when trying to render a collection of data by mistakenly returning the object when applying the map method instead of using the data from the object to create and return JSX.
To get promise value in React and JavaScript, we can use await . to create the getAnswer function that calls fetch with await to get the response data from the promise returned by fetch . Likewise, we do the same with the json method. And then we call setAns to set the value of ans .
To render an array of objects in React, we can use the array map method. const Item = (props) => { return <li>{props. message}</li>; }; const TodoList = () => { const todos = ["foo", "bar", "baz"]; return ( <ul> {todos. map((message) => ( <Item key={message} message={message} /> ))} </ul> ); };
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With