0

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.

2 Answers 2

1

In react each component have state and when their state change they are automatically updated by react. To achieve what you want you should use useState hook. Call to API should also be wrapped in something called useEffect. This way it will only be triggered when the component is mounted. You can read more here.

function Title(){
    const [ curTemp, setCurTemp ] = React.useState(null)

    React.useEffect( () => {
        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 => { setCurTemp( weather.main.temp )})
            // now curTemp will be updated and react recreate this component to display correct value.
        })
    }, [])

    return(
        <main>
            <h1>Weather Condition</h1>
            <h2>Current temperature is: {curTemp}</h2>
            <img></img>

        </main>
    )
}}

Sign up to request clarification or add additional context in comments.

Comments

1

When your recieve your fetched data react component is already rednered. You need to rerender it to show your data.

P.S. useEffect to prevent refetch of data again after second rerender.It will refetch only if navigator.geolocation is changed

import React, {useState, useEffect} from 'react';

function Title() {
  let [curTemp, setCurTemp] = useState();

  useEffect(() => {
    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 => {
              setCurTemp(weather.main.temp);
            });
      });
    }
  }, [navigator.geolocation]);

  return (
      <main>
        <h1>Weather Condition</h1>
        <h2>Current temperature is: {curTemp}</h2>
        <img></img>

      </main>
  );
}


ReactDOM.render(<Title/>, document.getElementById("root"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.