Kiran
Kiran

Reputation: 15

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>
                )
                 )}
        </>
    )
}

Upvotes: 0

Views: 69

Answers (1)

user120242
user120242

Reputation: 15268

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).

Upvotes: 1

Related Questions