Multiple fetch requests with setState in React

前端 未结 1 1750
忘掉有多难
忘掉有多难 2021-01-01 02:40

I\'m writing a component that will make fetch requests to two different paths of a site, then set its states to the resulting response data. My code looks something like thi

相关标签:
1条回答
  • 2021-01-01 03:01
    export default class TestBeta extends React.Component {
        constructor(props){
            super(props);
            this.state = {
                recentInfo: [],
                allTimeInfo: []
            };
        }
    
        componentDidMount(){
            Promise.all([
                fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent'),
                fetch('https://fcctop100.herokuapp.com/api/fccusers/top/alltime')
            ])
            .then(([res1, res2]) => Promise.all([res1.json(), res2.json()]))
            .then(([data1, data2]) => this.setState({
                recentInfo: data1, 
                alltimeInfo: data2
            }));
        }
    

    If you return Promise in then handler, then it's resolved to value. If you return anything else (like Array in your example), it will be passed as is. So you need to wrap your array of promises to Promise.all to make it Promise type

    0 讨论(0)
提交回复
热议问题