Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Having a nightmare trying to pull data from a weather API and display it in React but when I run my code I get an 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."

My code is below:

export default function getWeatherFromApiAsync() {
  return fetch(
    "https://api.openweathermap.org/data/2.5/weather?q=brighton,uk&appid=8b609354454cdb6c5a7092a939861ace&units=metric"
  )
    .then((response) => response.json())
    .then((responseJson) => {
      return (
        <div className="App">
          {responseJson.map((weather) => (
            <div>
              <h6> {weather.coord.lon}</h6>
            </div>
          ))}
        </div>
      );
    })
    .catch((error) => {
      console.error(error);
    });
}

Any help appreciated!

like image 478
Finlay Jefferis Avatar asked Mar 09 '26 18:03

Finlay Jefferis


1 Answers

You can't render a default component from promise like that.

You can take a advantages of useState , useEffect hook to fetch and render data into the component.

You can learn more about React Hooks from this link.

And also your api response is a json object and you're trying to map over it.

Note: You can map over array type of data only.

Here is your working code of yours,

import { useEffect, useState } from "react";

const App = () => {
  const [data, setData] = useState({});
  useEffect(() => {
    const getWeatherFromApiAsync = async () => {
      const resopnse = await fetch(
        "https://api.openweathermap.org/data/2.5/weather?q=brighton,uk&appid=8b609354454cdb6c5a7092a939861ace&units=metric"
      );
      const resopnseJson = await resopnse.json();
      console.log("json", resopnseJson);
      setData(resopnseJson);
    };
    getWeatherFromApiAsync();
  }, []);

  return (
    <div className="App">
      <h6>{data?.coord?.lon}</h6>
    </div>
  );
};

export default App;

like image 50
Pradip Dhakal Avatar answered Mar 12 '26 06:03

Pradip Dhakal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!