M
M
mag1st3r2019-07-07 20:00:15
JavaScript
mag1st3r, 2019-07-07 20:00:15

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

2 answer(s)
0
0xD34F, 2019-07-07
@mag1st3r

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));
  }
}

V
Vladimir, 2019-07-07
@Casufi

https://habr.com/ru/post/337030/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question