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!
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;
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