A
A
Andrew2021-03-09 13:12:23
API
Andrew, 2021-03-09 13:12:23

How to make asynchronous requests when rendering a component?

Good day! I am writing a simple react-application for viewing the weather (I use the openweathermap api). How to make queries when rendering a component? I use useEffect, everything works, but notifications creep out
604746444fbf0510128023.png
Repository: https://github.com/AndShir93/weather.git .

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor, 2021-03-09
@wug1

Each hook (that is, a function) requires a second dependency argument, since it is important for it to understand what value will be contained at the time of its execution. If the dependency is updated, then the function will be executed.
As a rule, such errors are also highlighted by ESLint, for example.
But a situation may arise when a variable specified in dependencies will cause an infinite loop, because something changes it from the outside. In your case, the getCity variable updates the coords fieldin the global state, this is what triggers the re-render. It makes sense to think about the order in which these requests are called, for example, call only one function (which will execute two requests asynchronously), i.e. hide this logic under the hood of the request itself. For example, first we get the city (even though we have it by default, Izhevsk), then, if the request for getting the city updated the coordinates for us and they even exist, we execute the request for the weather.
To refine the current implementation, you can execute the question in separate hooks so as not to depend, and separate the logic: a city cannot exist without coordinates, etc. At the same time, it will not cause infinite loops.

useEffect(() => {
        dispatch(getCity(city)) 
    }, [city, dispatch])

    useEffect(() => {
        // если координаты появились/обновились, получаем погоду
        if (coords) {
            dispatch(getWeather(coords))
        }
    },  [dispatch, coords])

Try it, there is a lot of material on the net on this topic.
https://medium.com/@andrewmyint/infinite-loop-insi...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question