Home > Net >  Why does React app fail when I reload page
Why does React app fail when I reload page

Time:09-20

I am busy learning javascript, and it, as well as react, nodejs and npm are all brand new concepts to me, so bear with me.

I have managed to piece together an application which returns the weather for my location by following this tutorial: console when I reload when it works

useEffect(() => {
    const fetchData = async () => {
      navigator.geolocation.getCurrentPosition(function(position) {
        setLat(position.coords.latitude);
        setLong(position.coords.longitude);
      });

      await fetch(`${process.env.REACT_APP_API_URL}/weather/?lat=${lat}&lon=${long}&units=metric&APPID=${process.env.REACT_APP_API_KEY}`)
      .then(res => res.json())
      .then(result => {
        setData(result)
        console.log(d)                      // (GL)
        console.log("Latitude is:", lat)    // (GL)
        console.log("Longitude is:", long)  // (GL)
        console.log(result);
      });
    }
    fetchData();
  }, [lat,long])

CodePudding user response:

The problem is that your fetchData function is an async function. So when you call fetchData, you'll need a .then() to make sure that it gets the result. Also your useEffect inner function should be async

useEffect(async () => {
    const fetchData = async () => {
      navigator.geolocation.getCurrentPosition(function(position) {
        setLat(position.coords.latitude);
        setLong(position.coords.longitude);
      });

      await fetch(`${process.env.REACT_APP_API_URL}/weather/?lat=${lat}&lon=${long}&units=metric&APPID=${process.env.REACT_APP_API_KEY}`)
      .then(res => res.json())
      .then(result => {
        setData(result)
        console.log(d)                      // (GL)
        console.log("Latitude is:", lat)    // (GL)
        console.log("Longitude is:", long)  // (GL)
        console.log(result);
      });
    }
    fetchData().then(result => {
        //do stuff (or await this fetch data)
    });
  }, [lat,long])

CodePudding user response:

You should remove the react-strict wrapper component.

Also - makes no sense writing await fetch when you're using the promise syntax then...

You need so split the logic within the useEffect because you are setting a state within the getCurrentPosition callback, and at the same time listen to a state change in the dependency array of that useEffect...

// this useEffect will only fire when the component mounts (once)
useEffect(() => {
    navigator.geolocation.getCurrentPosition(location => {
        // you should validate the response before setting the state...
        setLat(location.coords.latitude);
        setLong(location.coords.longitude);
    });
}, [])

// this useEffect will be called one the component mounts   when any dependency changes (lat/long)
useEffect(() => {
    fetch(`${process.env.REACT_APP_API_URL}/weather/?lat=${lat}&lon=${long}&units=metric&APPID=${process.env.REACT_APP_API_KEY}`)
        .then(res => res.json())
        .then(result => {
            setData(result)
            console.log(d)                      // (GL)
            console.log("Latitude is:", lat)    // (GL)
            console.log("Longitude is:", long)  // (GL)
            console.log(result);
    });
}, [lat, long])

Even though this is correct, this is considered bad code, and should be split between separate files for dealing with the API/actions/utility methods..etc.

  • Related