Last active
October 17, 2018 06:17
-
-
Save chenyong/29c04841d728b6c3f0808c57aed9fa05 to your computer and use it in GitHub Desktop.
ImmerState function with types
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
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