Search code examples
javascriptreactjspromisearrow-functionsresolve

new Promise with set state receives an arrow function


I was going through a react code base where I see the Promise function calling setstate with 2 arguments, I cannot exactly decipher how exactly this is working, everywhere I have seen a setState being created having one object argumemnt, but here we have a resolve argument that gets a setstate with an object and an arrow function which is calling resolve. The other arrow function, which I don't have any idea what it's doing and how this code is working

this is what I have for state

constructor(props){
        super(props);
        this.state = {
            articles:[],
            loading:true,
            page:1,
            totalResults : 0
        }
    }

This is the code that I have in my codebase which I have trouble understanding.

handleNextClick = async ()=>{
    await new Promise(resolve => this.setState({page: this.state.page+1}, () => resolve())); // same as await this.setState({page: this.state.page+1});
    await this.updateNews();
}

As you can see Promise is receiving theresolve arrow function which is calling setstate with an object and an arrow function. Can someone please explain how this is working exactly.


Solution

  • The code doesn't make a lot sense which is probably why it's difficult to understand.

    setState has a callback option. So you don't need a promise, and you don't need to await the setState either. Further, you probably don't need to await updateNews either so you can remove the async from the handleNextClick function.

    This is likely what the function should look like.

    handleNextClick () {
    
      // Set the new state, then use the callback option
      // to call `updateNews`
      this.setState( { page: this.state.page + 1 }, () => {
        this.updateNews();
      });
    }