So I am trying to display the location and the weather for the next couple of days but I am just having a hard time displaying the data in the ui - I am pretty new to react, would really appreciate any inputs
Here is the code in codesandbox
import "./styles.css";
import React, { useState, useEffect } from "react";
// goal : to display the weather shown every 3 hours for the next days
export default function App() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const api = "https://api.met.no/weatherapi/locationforecast/2.0/complete?lat=-16.516667&lon=-68.166667&altitude=4150";
useEffect(() => {
if (!api) return;
setLoading(true);
fetch(api)
.then((response) => response.json())
.then(setData)
.then(() => setLoading(false))
.catch(setError);
}, []);
console.log(data)
if (loading) return <h1>Loading...</h1>;
if (error) return <pre>{JSON.stringify(error, null, 2)}</pre>;
if (!data) return null;
if (data) {
return (
<div className="Layout">
<p> Cordinates here </p>
<p>{data.geometry.coordinates[0]}</p>
{data.geometry.coordinates.map((i) => (
<ul key={i.geometry}>
<li>{i.coordinates}</li>
</ul>
))}
<p> Timeseries here </p>
{data.properties.timeseries.map((i) => (
<ul key={i.timeseries}>
<li>{i.timeseries}</li>
</ul>
))}
</div>
);
}
return <div> Could not get the data</div>;
}
There is some issue in how you handled the map method. Edit it as follows
import React, { useState, useEffect } from "react";
// goal : to display the weather shown every 3 hours for the next days
export default function App() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const api = "https://api.met.no/weatherapi/locationforecast/2.0/complete?lat=-16.516667&lon=-68.166667&altitude=4150";
useEffect(() => {
if (!api) return;
setLoading(true);
fetch(api)
.then((response) => response.json())
.then(setData)
.then(() => setLoading(false))
.catch(setError);
}, []);
console.log(data)
if (loading) return <h1>Loading...</h1>;
if (error) return <pre>{JSON.stringify(error, null, 2)}</pre>;
if (!data) return null;
if (data) {
return (
<div className="Layout">
<p> Cordinates here </p>
<p>{data.geometry.coordinates[0]}</p>
{data.geometry.coordinates.map((i) => (
<ul key={i.geometry}>
<li>{i}</li>
</ul>
))}
<p> Timeseries here </p>
{data.properties.timeseries.map((j) => (
<ul key={j.timeseries}>
<li>{j.time}</li>
</ul>
))}
</div>
);
}
return <div> Could not get the data</div>;
}
Codesandbox here