Last active
March 3, 2018 12:54
-
-
Save mgtitimoli/e43c688cd72f71f41f2d8e664335392b to your computer and use it in GitHub Desktop.
Promisified Conditional setState
This file contains 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
// @flow | |
import {curry} from "flow-static-land/lib/Fun"; | |
import type {ComponentType, ElementRef} from "react"; | |
type State = Object; | |
type Updater<Props: Object> = (prevState: State, props: Props) => State; | |
const setState = <Props: Object>( | |
updater: Updater<Props>, | |
component: ElementRef<ComponentType<Props>>, | |
newProps?: Props // to be used in componentWillReceiveProps | |
): Promise<ElementRef<ComponentType<Props>>> => | |
new Promise(resolve => { | |
const newState = updater(component.state, newProps || component.props); | |
if (newState === component.state) { | |
resolve(component); | |
} else { | |
component.setState(newState, () => resolve(component)); | |
} | |
}); | |
export default curry(setState); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mgtitimoli very nice!
What about adding a couple of usage samples and even create an npm package out of it?