简体   繁体   中英

handling 2nd response when doing multiple GET requests in React

I've manage to pass the first response into the state name data (this.state.data) of the component. But when I trying doing a second request for data1 from another API, it's not showing up. Both responses are good from checking in dev tool and the first one I can use the data.

class WeatherApp extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    error: null,
    isLoaded: false,
    data: [],
    data1: []
  };
}

componentDidMount() {
  Promise.all([
      fetch("weatherAPI.php"),
      fetch("weatherAPIToday.php")
    ]).then(([res, res1]) => res.json())
    .then((result, result1) => {
        this.setState({
          isLoaded: true,
          data: result,
          data1: result1
        }, console.log(result));
      },

      (error) => {
        this.setState({
          isLoaded: true,
          error
        });
      }
    );
}

Because both res and res1 return a promise, all you have to do is wrap them both in a Promise#all

Promise.all([
    fetch("weatherAPI.php"),
    fetch("weatherAPIToday.php")
]).then(([res, res1]) => Promise.all(res.json(), res1.json()))
.then((result, result1) => {
    this.setState({
        isLoaded: true,
        data: result,
        data1: result1
    }, console.log(result));
})
.catch(error => {
    this.setState({ isLoaded: true, error });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM