score:0

Accepted answer

for this you could make the second useeffect dependent on your latitude and longitude states:

   useeffect(()=>{
    
    axios.get(`${api.base}weather?lat=${latitude}&lon=${longitude}&units=metric&appid=${api.key}`).then
     ((response) => {
         console.log(response.data)
      })

   },[latitute, longitude])

this will call the useeffect every time the latitude or longitude states have changed.

score:0

your useeffects are both running asynchronously after the first render. if you need them to be ordered, then you should run them together in the same useeffect and add your code to fetch the response within the success callback of getcurrentposition.

see this example:

useeffect(() => {
  const fetchdata = async() => {
    navigator.geolocation.getcurrentposition((position) => {
        setlatitude(position.coords.latitude)
        setlongitude(position.coords.longitude);

        const response = await axios.get(`${api.base}weatherlat=${position.coords.latitude}&lon=${position.coords.longitude}&units=metric&appid=${api.key}`);
      });
    });
}, []);

note: setstate is also asynchronous, hence why we use the return position directly for the axios fetch request.

an alternative to this is, as the other answer mentioned, having your second useeffect use [latitude, longitude] in the deps array but if you don't want to constantly fetch weather api data every single time the lat/long changes, then you can just do it this way to run this once on initial component mount.


Related Query

More Query from same tag