Answer the question
In order to leave comments, you need to log in
How to correctly execute queries in a loop?
I make a request to the server through a map with different urls, then I set the received data to the State and use it for output. I want the requests to be consistent, but sometimes they do not work correctly and bugs are obtained. How to correctly write the code for normal data acquisition?
const urlList = ["countries", "states", "cities", "users"];
componentDidMount() {
urlList.map( (url, index) => {
return servicesAPI.getResourse(url).then( (body) => {
index !== 3 ? this.setState({
dataAPI : [...this.state.dataAPI, body] }) :
this.setState({
dataAPI : [...this.state.dataAPI, body],
loaded: true
})
})
})
export default class ServicesAPI {
_apiBase = `http://localhost:3001/`;
async getResourse(url) {
const res = await fetch(`${this._apiBase}${url}`);
if (!res.ok) {
throw new Error(`Could not fetch ${url}` +
`, received ${res.status}`)
}
return await res.json();
}
Answer the question
In order to leave comments, you need to log in
async componentDidMount() {
for (const url of urlList) {
const
dataAPI = [ ...this.state.dataAPI, await servicesAPI.getResourse(url) ],
loaded = dataAPI.length === urlList.length;
await new Promise(r => this.setState({ dataAPI, loaded }, r));
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question