Skip to content

Instantly share code, notes, and snippets.

@chenyong
Last active October 17, 2018 06:17
Show Gist options
  • Save chenyong/29c04841d728b6c3f0808c57aed9fa05 to your computer and use it in GitHub Desktop.
Save chenyong/29c04841d728b6c3f0808c57aed9fa05 to your computer and use it in GitHub Desktop.
ImmerState function with types
import React from "react";
import produce from "immer";
// get type of partial of an object with type T
export type IPartialObject<T> = { [K in keyof T]?: T[K] };
export interface ImmerStateFunc<S> {
(f: IPartialObject<S> | ((s: S) => void), callback?: () => void): void;
}
export let immerHelpers = {
setState: (...f: any[]) => void {},
immerState: function<S>(f: IPartialObject<S> | ((s: S) => void), callback?: () => void) {
if (typeof f === "function") {
this.setState(produce<any>(f as (s: S) => void), callback);
} else {
let partialState = f;
let newState = produce<S>((state) => {
Object.assign(state, partialState);
});
this.setState(newState, callback);
}
},
};
interface IState {
isLoading: boolean;
isLoaded: boolean;
}
// actual usage
class A extends React.Component<any, IState> {
render() {
return null;
}
immerState = immerHelpers.immerState as ImmerStateFunc<IState>;
onchange() {
this.immerState({
isLoading: true,
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment