Home > Enterprise >  How to wait for value before running fetch?
How to wait for value before running fetch?

Time:10-20

my first post here with what is probably a pretty easy question. I am trying to get the lat and long values to actually be something before being fed into the URL. Most of the time I get an error returned for a bad request because the lat and long values haven't propagated yet.

Thanks!

Code is here (edited out API keys):

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


      const url =
        await `https://api.openweathermap.org/data/2.5/weather/?lat=${lat}&lon=${long}&units=metric&APPID=DELETED`;
     
      await fetch(url)
        .then((response) => {
          return response.json();
        })
        .then((result) => {
          setData(result);
        })
        .catch(console.error);
    };

    fetchData();
  }, [lat, long]);


CodePudding user response:

It seems that lat and long are set in the useEffect using them. You should probably set them before using them in another useEffect.

useEffect(() => {
      navigator.geolocation.getCurrentPosition(function (position) {
        setLat(position.coords.latitude);
        setLong(position.coords.longitude);
      });
}, [])

useEffect(() => {
  const fetchData = async () => {

      const url = `https://api.openweathermap.org/data/2.5/weather/?lat=${lat}&lon=${long}&units=metric&APPID=DELETED`;
     
      await fetch(url)
        .then((response) => {
          return response.json();
        })
        .then((result) => {
          setData(result);
        })
        .catch(console.error);
    };

    if (lat && long) {
      fetchData();
    }
  }, [lat, long]);

CodePudding user response:

Either you have to store those values in your function or you have to wait until the state is updated. State is asynchronous and this is why you get this error.

  • Related