I'm trying to make a Weather App in React but for some reason, I'm having some issues while fetching data. When I try to assign fetched data to my variable, nothing happens and the variable remains undefined. Here's the code
function Title(){
let curTemp;
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition((position) => {
let lat = position.coords.latitude;
let long = position.coords.longitude;
fetch(`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=ba54c777cc51ef2eb1d2bdd0760f0908&units=metric`)
.then(response => response.json())
.then(weather => {curTemp=weather.main.temp})
console.log(curTemp)
})
return(
<main>
<h1>Weather Condition</h1>
<h2>Current temperature is: {curTemp}</h2>
<img></img>
</main>
)
}}
ReactDOM.render(<Title />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Here, I tried to assign the temperature I fetched to a "curTemp" variable but nothing happens. I assume this is because React does this differently than vanilla JavaScript but I haven't figured out in which way.