129

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?

4
  • 1
    You can only ever return 1 object from react. You need to change return posts.map to const someVar = posts.map, and then return <ul>{someVar}</ul> ... that way, you're returning a wrapped object. reactjs.org/docs/lists-and-keys.html
    – Aaron
    Dec 5, 2017 at 16:59
  • 8
    while the first comment is true, the larger problem is that you're trying to return JSX from an async method which won't work. you need to fetch your async data in componentDidMount() and call this.setState when your api returns instead of returning JSX directly
    – azium
    Dec 5, 2017 at 17:04
  • 1
    I tried this before with componentWillMount because I assumed that was the issue but it didn't work. Just did it with componentDidMount and it worked! Thanks azium.
    – Aaron
    Dec 5, 2017 at 17:13
  • Obligatory "I know this is old, but...". @azium 's comment saved me. If you run into this... Another dev had thrown an async on the component function. This error did not encourage me to check that... Thanks, azium :)
    – Paul Wade
    Jan 22 at 14:11

6 Answers 6

130

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

6
  • 6
    This fixed it for me - the stacktrace didn't really give away that this was the issue!
    – Tom
    Jul 8, 2019 at 7:59
  • 4
    Neither render function in a class components can be async i.e return a Promise.
    – Alireza
    Sep 28, 2019 at 7:51
  • 15
    Exactly. Instead of implementing async/await directly on the functional component, I added useEffect hook inside the functional component like this useEffect(async () => {//code with await keyword here}, []) and all worked fine May 19, 2020 at 11:13
  • 4
    @EranG the async func' should be inside like this useEffect( () => { async function fetchData(){ //code with await keyword here } fetchData(); }, []); The useEffect callback cannot be async. Jul 29, 2021 at 10:46
  • lifesaver, I was trying to figure out what was causing this error when converting class components to functional and I had made the component async! Feb 3, 2022 at 20:46
61

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

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>
}
2
  • 2
    The useEffect callback cannot be async, as pointed out in this article which is referenced in the docs Jul 12, 2021 at 11:19
  • 1
    @ajrussellaudio but he can do like this... useEffect( () => { async function fetchData(){ try { const res = await axios.get('/posts'); setPosts(res.data); } catch (err) { console.log(err); } } fetchData(); }, []); Jul 29, 2021 at 10:41
1

Poor me

For anyone using jest test

And trying to call a function children then received this Error

please check:

const children = jest.fn().mockReturnValueOnce(null)

NOT

const children = jest.fn().mockRejectedValue(null);
1

If you use Next.js you can use this: Put your codes in {}, if you have some connection or some calculations thats need time, add await to your codes in {}.

import { useEffect } from 'react'

useEffect(async () => {.......},[])
1

You can try using useState and pass the setter function as a parameter to the async function that gets the posts from the server. Hope this helps.

function getPostElement(post, i){
    return <li key={i} className="list-group-item">{post.text}</li>;
}

async function getNewPosts(setPosts){
    const posts = await axios.get('/posts');
    const newPostElements =  posts.map((post,i) => getPostElement(post, i));

    setPosts(newPostElements);
}

function renderPosts(){
    const [posts, setPosts] = useState([]);
    getNewPosts(setPosts);

    return (
        <div>
            <ul className="list-group list-group-flush">
                {posts}
            </ul>
        </div>
    );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.