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 } )
} )
}