Created
April 20, 2018 23:50
-
-
Save wesleybliss/7ea5b42100c319b3ca9751c1d13b0f0d to your computer and use it in GitHub Desktop.
Asynchronous setState for React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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