estin8
estin8

Reputation: 53

How to wait for value before running fetch?

Edit: I ended up using axios instead of fetch and it works great. Just removed the response.json() and switch fetch to axios.get.

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]);


Upvotes: 3

Views: 502

Answers (2)

edarv
edarv

Reputation: 371

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]);

Upvotes: 5

Sabshane
Sabshane

Reputation: 241

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.

Upvotes: 1

Related Questions