Multiple fetch requests with setState in React

12,933
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

Share:
12,933
albert
Author by

albert

Hey all, I come from an (non electrical or computer) engineering background. Most of my undergrad studies at Cal mostly have to do with structural engineering/construction materials. I have an avid interest in programming, but haven't really ever been able to take any computer science class (aside from a Matlab class). My knowledge is pretty limited, so bear with me!

Updated on June 19, 2022

Comments

  • albert
    albert almost 2 years

    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 this:

    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]) => [res1.json(), res2.json()])
            .then(([data1, data2]) => this.setState({
                recentInfo: data1, 
                alltimeInfo: data2
            }));
        }
    

    However, when I go to render my two states, I find that they are actually still empty, and in fact have not been set to anything. I feel like I might be using either the Promises or fetch() API wrong, or misunderstanding how setState works, or a combination of things. I tested around and found that after the first then(), my data1 and data2 were still Promises for some reason, and had not become actual JSON objects yet. Either way, I cannot figure out for the life of me what's going on here. Any help or explanation would be appreciated