简体   繁体   中英

cannot read property of map undefined react

I am a newbie react learner and here trying to make an api call to display list of weather details(for test case I am trying to get "app_max_temp") but I am getting error as "cannot read property of map undefined at SearchCity(SearchCity.js:29)".I have tried that url in postman and works absolutely fine giving response data. I have my code below. I can't figure out what is wrong and how to solve it. Any help would be appreciated. Thanks in advance.

import React,{useState} from 'react';

export default function SearchCity(){

    const[query,setQuery] = useState('');
    const[weatherResponse,setWeatherResponse] = useState([]);

    const searchCity = async (e) =>{
        e.preventDefault();
        const api_key ="YourApiKey";
        const url = `https://api.weatherbit.io/v2.0/forecast/daily?city=${query}&key=${api_key}`;
        try{
            const res = await fetch(url);
            const data = await res.json();
            console.log(data.results);
            setWeatherResponse(data.results);
        }
        catch(error){
            console.error(error);
        }

    }

    return(
        <>
            <form className="form" onSubmit={searchCity}>
                <label className="cityTitle" htmlFor="query">City Name : </label>
                <input type="text" value={query} name="query" onChange={(e)=>setQuery(e.target.value)} />
                <button className="btnSearch" type="submit">Search</button>
            </form>  
                {weatherResponse.map(res=>(
                <p>{res.app_max_temp}</p>
                )
                 )}
        </>
    )
}

Weatherbit 16 Day Forecast API Documentation
Weatherbit 16 Day Forecast Swagger UI

The API returns those values in property data, not result:

        console.log(data.data);
        setWeatherResponse(data.data);

Make sure you have a proper API key (don't post it on here of course).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM