Created
December 10, 2018 11:47
-
-
Save chenyong/262c3b1d81f8952d3e63f1de183744c7 to your computer and use it in GitHub Desktop.
Helper functions to use Immer in React projects.
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 produce from "immer"; | |
export interface ImmerStateFunc<S> { | |
(f: ((s: S) => void)): Promise<any>; | |
} | |
export interface MergeStateFunc<S> { | |
(partialState: Partial<S>): Promise<any>; | |
} | |
export let immerHelpers = { | |
setState: (...f: any[]) => void {}, | |
async immerState<S>(f: ((s: S) => void)): Promise<any> { | |
return new Promise((resolve) => { | |
this.setState(produce<any>(f), () => { | |
resolve(); | |
}); | |
}); | |
}, | |
async mergeState<S>(partialState: Partial<S>): Promise<any> { | |
let newState = produce<S>((state) => { | |
Object.assign(state, partialState); | |
}); | |
return new Promise((resolve) => { | |
this.setState(newState, () => { | |
resolve(); | |
}); | |
}); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment