when i run npm my site works perfect but when i add the value {((data.main.temp)-273.15).toFixed . it gets blank.
when i remove it my page come live again help me to fix this.
i am creating weather site with react js. the site works fine without that value but when i add that value the page get blanked. here is my code
when i run npm my site works perfect but when i add the value {((data.main.temp)-273.15).toFixed . it gets blank.
when i remove it my page come live again help me to fix this.
i amc reating weather site with react js. the site works fine without that value but when i add that value the page get blanked. here is my code
import axios from "axios";
import React, { useEffect, useState } from "react";
import './style.css';
export function Weather (){
const apikey = "1815b2003ad4cef38e6b16343a9034ca"
const [input, setInput] = useState ("")
const [data, setData] = useState({})
const getdetail = (cityName) => {
const apiURL = "https://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&appid=" + apikey
axios.get(apiURL).then((res)=>{
console.log("response",res.data)
setData (res.data)
}).catch((err)=> {
console.log("err", err)
})
}
const handleinput = (e) =>{
setInput(e.target.value)
}
const handle = () => {
getdetail(input)
}
useEffect(()=>{
getdetail("delhi")
}, [])
return(
<>
<div className="col-md-12">
<div className="weat">
<div className="container">
<h2 className="hed">Weather</h2></div>
<img className="img-fluid" src="bc.jpg" alt="" />
<div><h3>{data.name}</h3></div>
<div><h2>{((data.main.temp)-273.15).toFixed (2)}°C</h2></div>
<div className="container in
">
<input type="text" value={input} onChange={handleinput}/><br/><br/>
<button className="btn btn-danger" onClick={handle}>button </button>
</div>
</div>
</div>
</>
)
}
2
Answers
Check type of this exprsession ((data.main.temp)-273.15)
I suppose, that this expression ((data.main.temp)-273.15) can be undefined, because when this page renders first time you have empty object in your state, because function getdetail – is async function.
Either do:
Or:
You also have space between
.toFixed
and the()
but that should not be causing issues. Most likely it’s because you are trying to read a key out of data, when data is undefined, because the first render happens before the async call for data is resolved.