Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects are not valid as a React child (found: [object Promise])

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?

like image 417
Aaron Avatar asked Dec 05 '17 16:12

Aaron


People also ask

How do you fix 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?

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.

Why objects are not valid as React child?

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.

How do you get data from Promise object React?

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 .

How do you render an array of objects in React?

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> ); };


1 Answers

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

like image 52
Padhraic Avatar answered Oct 14 '22 23:10

Padhraic