0

My interface code relies on a number of sequential steps, for example:

getData()
.then( ( data ) => this.updateHistory(data) )
.then( this.changeInterface )

Where functions like this.updateHistory and this.changeInterface change the state.

I know that this.setState accepts a callback, so in those functions I do things like:

updateHistory(data){
  this.setState( {new: data}, ( callback ) => {
    this.props.dispatch( updateRelevantRedux() )
    .then( () => doAnotherImportantThing() )
    .then( () => {
       const important = createImportant()
       if ( important > 99 ) this.setState( { essential: important } )
     } )
  } )
}

But this often leads to hard to read callback-hell-like code. I'd like to be able to call this.setState as a promise to I can:

  • write easy to read code
  • easily create promise chains where I'm sure the state is updated

Like this for example:

updateHistory(data){
    return this.setState( { new: data } )
    .then( () => this.props.dispatch( updateRelevantRedux() ) )
    .then( () => doAnotherImportantThing() )
    .then( () => {
       const important = createImportant()
       if ( important > 99 ) return this.setState( { essential: important } )
     } )
}
Mentor
  • 965
  • 9
  • 21
  • It's interesting that this is marked duplicate and downvoted. Yes, this is an extension of translating any callback to a promise, but I get this question a lot and people seem not to be able to find the answer. – Mentor Sep 30 '18 at 19:20

1 Answers1

-3

You can leverage the callback functionality to create a promise version of the setState function. In your class constructor you can for example create a promise friendly setState like this:

this.promiseState = state => new Promise( resolve => this.setState( state, resolve ) )

Or written in less terse js:

this.promiseState = ( state ) => {
    return new Promise( ( resolve ) => {
        this.setState( state, resolve )
    } )
}

Which are es2017+ versions of writing:

this.promiseState = function ( state ) {
    return new Promise( function ( resolve, reject ) {
        this.setState( state, function() {
            resolve()
        } )
    } )
}
Mentor
  • 965
  • 9
  • 21