2

I make a request to the server via a map with different urls, then I set the data in State and use it for output. I want the requests to be consecutive but sometimes they do not work correctly and get bugs, how to write the code for normal data retrieval?

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();
    }
3
  • There are two await keyword inside getResource func. It should be only one. Commented Jul 8, 2019 at 13:11
  • not sure why you are using map to loop over the array since you are not using it to map anything. Commented Jul 8, 2019 at 13:12
  • Using promises? var promises = []; urlList.forEach( function(element) { promises.push(yourRequest); }); Promise.all(promises).then(results => { ... }); Commented Jul 8, 2019 at 13:14

1 Answer 1

1

Use of Promise.all();

componentDidMount() {
     const fetchPromises = [];
     urlList.forEach( (url, index) => {
        fetchPromises.push(servicesAPI.getResourse(url));
     });

     const allResourcesPromise = Promise.all(fetchPromises);
     allResourcesPromise.then(data => {
        // list with responses
     }).catch(err => {
        console.log(err.toString());
     });

}

Sample example: https://jsbin.com/vevufumano/1/edit?html,js,console,output

Also instead of then, where is possible, you can use async/await for more cleaner code.

Sign up to request clarification or add additional context in comments.

2 Comments

"I want the requests to be consecutive" – Your code will run them in parallel.
I appreciate your highlight. The requests are consecutive, keeping its order.

Your Answer

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