How to finish all fetch before executing next function in React?

后端 未结 3 1588
悲哀的现实
悲哀的现实 2021-02-01 04:06

Using ReactJS, I have two different API points that I am trying to get and restructure: students and scores. They are both an array of objects.

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 04:54

    I would recommend restructuring slightly - instead of updating your state after each fetch call completes, wait for both to complete and then update the state all at once. you can then use the setState callback method to run the next method you would like to.

    You can use a Promise library such as Bluebird to wait for multiple fetch requests to finish before doing something else

    import Promise from 'bluebird'
    
    getStudents = () => {
      return fetch(`api/students`, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      }).then(response => response.json());
    };
    
    getScores = () => {
      return fetch(`api/scores`, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      }).then(response => response.json());
    };
    
    Promise.join(getStudents(), getScores(), (students, scores) => {
        this.setState({
            students,
            scores
        }, this.rearrangeStudentsWithScores);
    });
    

提交回复
热议问题