Answer the question
In order to leave comments, you need to log in
How to implement fetch in React?
Hello. I made a weather app working with api. I'm interested in the question: how to transfer the result of fetch to the application itself so that the result can be displayed on the screen? I called a class that returns a promise, and in the same function I pushed the values into state. Am I doing it right, or is there some other way?
Here is a piece of app.js code:
state = { //initial state
weatherForecast: {
main: {},
wind: {},
weather: {
0: []
}
},
isLoading: true,
error: false
}
async getForecast (city) {
let response = await new WeatherService().getWeather(city); //get data from fetch
this.setState({ //push fetch data to state
weatherForecast: response,
isLoading: false
});
}
Answer the question
In order to leave comments, you need to log in
In general, everything is correct. But you can also use redux in another way, for example, and make requests in its middleware.
There is no point in creating a new service (new WeatherService) every time. You can create one instance at initialization. And in general there is no special sense to describe it in the form of a class.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question