React - Latitude And Longitude State Incorrect When Using `useEffect`
I have previously asked this question and implemented some changes relating to the article linked. However, I am still confused about how exactly to get what I need. I'm still new
Solution 1:
I think you're looking for a useEffect function like this:
useEffect(() => {
(async () => {
const res = await fetch(
`https://api.openweathermap.org/data/2.5/forecast?q=${input}&cnt=7&appid=38f1fbc74deb031d79636062ba66d984`
);
const data = await res.json();
//set states to include weather detail, and current longitude and latitude
setLat(data.city.coord.lat);
setLon(data.city.coord.lon);
const weatherInfo = [...new Set(data.list.map((item) => item))];
setForecast(weatherInfo);
})();
}, [input]);
Note the [input]
at the end. It ensures that the useEffect only gets called when input changes.
Your current code won't do anything when useEffect is called because all you do there is declare a function, rather than actually running it.
EDIT: We need to wrap the async function in useEffect function so it does not return a promise: React does not like that since the return value of a useEffect function has to be nothing OR a clean-up function.
Solution 2:
Try to replace your useEffect to something like this.
useEffect(() => {
(async() => {
await fetch(
`https://api.openweathermap.org/data/2.5/forecast?q=${input}&cnt=7&appid=38f1fbc74deb031d79636062ba66d984`
)
.then((res) => res.json())
.then((data) => {
//set states to include weather detail, and current longitude and latitude
setLat(data.city.coord.lat);
setLon(data.city.coord.lon);
const weatherInfo = [...new Set(data.list.map((item) => item))];
setForecast(weatherInfo);
});
})()
}, [input]);
Post a Comment for "React - Latitude And Longitude State Incorrect When Using `useEffect`"