Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active March 3, 2018 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgtitimoli/e43c688cd72f71f41f2d8e664335392b to your computer and use it in GitHub Desktop.
Save mgtitimoli/e43c688cd72f71f41f2d8e664335392b to your computer and use it in GitHub Desktop.
Promisified Conditional setState
// @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);
@gabmontes
Copy link

@mgtitimoli very nice!

What about adding a couple of usage samples and even create an npm package out of it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment