How to Fix the “Objects are not valid as a React child (found: [object Promise])” Error When Developing React Apps?

Sometimes, we may run into the “Objects are not valid as a React child (found: [object Promise])” Error when developing React apps.

In this article, we’ll look at how to fix the “Objects are not valid as a React child (found: [object Promise])” Error when developing React apps.

Fix the “Objects are not valid as a React child (found: [object Promise])” Error When Developing React Apps

To fix the “Objects are not valid as a React child (found: [object Promise])” Error when developing React apps, we should make sure the states we’re rendering aren’t set to promises.

For instance, we write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [val, setVal] = useState();

  const getAnswer = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const json = await res.json();
    setVal(json.answer);
  };

  useEffect(() => {
    getAnswer();
  }, []);

  return <div>{val}</div>;
}

We create the getAnswer function that gets data from an API with fetch.

Then we call res.json to convert the response data into a JSON object.

We put await before res.json to get the actual data object instead of a promise assigned to json.

Next, we call setVal to set val to the value of json.answer.

Then in the useEffect callback, we call getAnswer to get the data when the component mounts.

We pass in an empty array into useEffect to make sure the useEffect callback only runs when the component mounts.

And finally, we display the value of val in the div.

Conclusion

To fix the “Objects are not valid as a React child (found: [object Promise])” Error when developing React apps, we should make sure the states we’re rendering aren’t set to promises.