Skip to content

Instantly share code, notes, and snippets.

@wesleybliss
Created April 20, 2018 23:50
Show Gist options
  • Save wesleybliss/7ea5b42100c319b3ca9751c1d13b0f0d to your computer and use it in GitHub Desktop.
Save wesleybliss/7ea5b42100c319b3ca9751c1d13b0f0d to your computer and use it in GitHub Desktop.
Asynchronous setState for React
// e.g. src/lib/helpers.js
export const createAsyncSetState = context => {
return function(newState) {
return new Promise(resolve => {
context.setState(newState, resolve)
})
}.bind(context)
}
// Usage, e.g. MyComponent.jsx
class MyComponent extends Component {
state = {
someKey: null,
otherKey: null
}
someComponentFn = async => {
if (someCondition)
await this.setStateAsync({
...this.state,
someKey: 'foo'
})
if (someOtherCondition)
this.setState({
...this.state,
otherKey: 'bar'
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment