1

Good evening!

I am building weather app. So basically i have MAIN PAGE where i have my Search component for type city to get info about it. But when i am first render that page i don't see any info ofc it's obvious. So i want to getUserLocation and in the first component where i run my app i want to create useEffect with function inside it, then i get lat and lon from my import function then i make a request to API to get info about city based on user location. When i am get all info i will dispatch that data to my reducer and from reducer i will update my main.page. So it's works.I run my app, i see login page, under the hood i am getting user location then dispatch and upadate reducer then set info on main.page. When i am log in i can see that data but when i refresh page, data's gonne. So how to again run my useeffect Code below:

useEffect(() => {
        const updateDateBasedOnUserLocation = async () => {
            try{
                const {lat, lon} = await getCoords();
                console.log(lat, lon)
                const response = await fetch(`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${KEY}&units=metric`)
                console.log(response)
                const data = await response.json();
                console.log(data)
                dispatch(REQUEST_SUCCESS({
                    city: data.name,
                    temp: Math.round(data.main.temp),
                    feels_like: data.main.feels_like,
                    wind: data.wind.speed,
                    humidity: data.main.humidity,
                    pressure: data.main.pressure
                },))
            }
            catch(err) {
                console.log(err)
            }
        }
        updateDateBasedOnUserLocation()
    }, )

1 Answer 1

1

You need to pass an array of dependencies to useEffect.

If you want to run it only on the first render it should be empty.

useEffect(() => {
   // Do something
}, []);

If you want to run when a dependency change.

useEffect(() => {
   // Do something
}, [dependency]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.