0

I've a JSON as shown:

{
   "cod":"200",
   "message":0,
   "cnt":40,
   "list":[
      {
         "dt":1601024400,
         "main":{
            "temp":301.11,
            "feels_like":301.34,
            "temp_min":301.11,
            "temp_max":301.2,
            "pressure":1010,
            "sea_level":1010,
            "grnd_level":907,
            "humidity":58,
            "temp_kf":-0.09
         },
         "weather":[
            {
               "id":803,
               "main":"Clouds",
               "description":"broken clouds",
               "icon":"04d"
            }
         ],
         "clouds":{
            "all":68
         },
         "wind":{
            "speed":4.24,
            "deg":238
         },
         "visibility":10000,
         "pop":0.25,
         "sys":{
            "pod":"d"
         },
         "dt_txt":"2020-09-25 09:00:00"
      }
   ]
}  

I've written a React code to pull the data.
Code:

import React from 'react';
// async
import { useAsync } from 'react-async';

const loadUsers = async () =>
  await fetch("http://api.openweathermap.org/data/2.5/forecast?q=bengaluru&appid={API_KEY}")
    .then(res => (res.ok ? res : Promise.reject(res)))
    .then(res => res.json())
  

export default function Dashboard() {
   
    const { data, error, isLoading } = useAsync(
        { 
            promiseFn: loadUsers 
        }
    )
    if (isLoading) return "Loading..."
    if (error) return `Something went wrong: ${error.message}`
    console.log("Data is", data)
    if (data)

    return (
        <div className="container">
            <div className="App">
                <h2>Weather Details</h2>
            </div>
            {data.list.map((weather, index) => (
                <div key={index} className="row"> 
                <div className="col-md-12">
                    <p>{weather.temp_min}</p>
                    <p>{weather.temp_max}</p>
                </div>
                </div>
            ))}
        </div>
    )

}  

But it is empty as shown here...
Dashboard
How can I pull the data?

Ajay Kulkarni
  • 2,900
  • 13
  • 48
  • 97

1 Answers1

2

I'm not sure if your data is actually being pulled into the frontend, but if it is, I think the issue is when you map over it. When you use data.list.map((weather, index) => (, in that instance weather is each item in list. So instead of weather.min_temp (which doesn't exist) I think you're looking for weather.main.min_temp and weather.main.max_temp.

{data.list.map((weather, index) => (
    <div key={index} className="row"> 
    <div className="col-md-12">
        <p>{weather.main.temp_min}</p>
        <p>{weather.main.temp_max}</p>
    </div>
    </div>
))}

As an aside, it's not recommended to use index as a key. Maybe the dt is a unique value that you can use as a key?

larz
  • 5,724
  • 2
  • 11
  • 20