initially its showing output but on search giving this error-"Unhandled Rejection (TypeError): Cannot read property 'lon' of und | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

initially its showing output but on search giving this error-"Unhandled Rejection (TypeError): Cannot read property 'lon' of und

import React, { useState, useEffect } from 'react' const First = () => { const [city, setcity] = useState(null); const [search, setsearch] = useState("mumbai"); const [longitude, setlongitude] = useState(""); useEffect(() => { const fetchapi = async () => { const url = `http://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid={api_key}`; const response = await fetch(url); const resjson = await response.json(); console.log(resjson.coord.lon); setlongitude(resjson.coord.lon); setcity(resjson.main); } fetchapi(); }, [search]); return ( <div className="first"> <div className="App"> <h1>WEATHER APP 1</h1> <input type="search" className="input" value={search} onChange={(event) => { setsearch(event.target.value) }} /> {!city ? (<p>no data found</p>) : ( <> <div> <h2 >{search}</h2> <h3 >{city.temp}&deg; cel</h3> <h3 >Min : {city.temp_min}&deg; cel | Max : {city.temp_max}&deg; cel</h3> <h4>longitude : {longitude}</h4> </div> </> )} </div> </div> ) } export default First

23rd Jun 2021, 5:04 PM
dheeraj gupta
dheeraj gupta - avatar
1 Answer
+ 1
Try resjson.coord?.lon Since you have controlled resjson, however rsjson.coord might be undefined if search has not formed a city name while typing. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined.
24th Jun 2021, 10:17 AM
Calviղ
Calviղ - avatar