Home > Software engineering >  Handle react fetch with Openweather Api
Handle react fetch with Openweather Api

Time:11-12

I'm building a simple app with React (I'm learning it). I don't understand how to render the data object correcly since I can't write day.key to access the information I want to print. Can you help me?

Here is the code I'm using: Fetch request:

import { useEffect, useState } from "react";
import Day from './Day';

const DayList = () => {
    const [data, setData] = useState();

    useEffect(() => {
        const lat = 45.68;
        const long = 9.23;
        const apikey = "apikey";

        fetch("https://api.openweathermap.org/data/2.5/onecall?lat=" lat "&lon=" long "&exclude=current,minutely,hourly&appid=" apikey)
        .then((res) => res.json())
        .then((data) => {
            setData(data.daily)
        })
    }, [])

    return (
        <div className="day-list">
            { data && <Day data = { data } /> }
        </div>
    );
}
 
export default DayList;

Here is the render component where I don't know how to access data

const Day = ( {data} ) => {
    return (
        <div>
            {Object.keys(data).map((day) => (
                <div className="day">{ ??? }</div>
            ))}
        </div>
    );
}
 
export default Day;

Example response can be found here;

Screen of the console response Thanks

CodePudding user response:

As you are setting data.daily as the data (state variable in your component), you need to use data.map to access the values as data.daily is an array.

const Day = ({ data }) => {
    return (
        <div>
            {data.map((day) => (
                <p>Temp: {day.temp}</p>
                <p>Feels Like: {day.feels_like}</p>
            ))}
        </div>
    );
}
 
export default Day;

CodePudding user response:

The data you get from your code is array and not object, so the result should be similar to this -

const Day = ( {data} ) => {
    return (
        <div>
            {data.map((day) => (
                <div className="day">{day.sunrise}</div>
                <div className="day">{day.sunset}</div>
                <div className="day">{day.temp.min}</div>
                <div className="day">{day.temp.max}</div>
                .....
            ))}
        </div>
    );
}

export default Day;
  • Related