immer#Immutable TypeScript Examples
The following examples show how to use
immer#Immutable.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: model.ts From reactant with MIT License | 5 votes |
model = <
S extends Record<string, any>,
A extends Record<string, (...args: any[]) => (state: S) => void>
>(
scheme: Scheme<S, A>
): Actions<A> & Service<S> & S => {
let module: Service<S>;
Object.keys(scheme.actions).forEach((key) => {
const fn = scheme.actions[key];
Object.assign(scheme.actions, {
[key]: (...args: any[]) => {
let state: Immutable<S> | S | undefined;
let patches: Patch[] | undefined;
let inversePatches: Patch[] | undefined;
if (module[enablePatchesKey]) {
[state, patches, inversePatches] = produceWithPatches(
module[stateKey],
(draftState: S) => {
fn(...args)(draftState);
}
);
} else {
state = produce(module[stateKey], (draftState: S) => {
fn(...args)(draftState);
});
}
const lastState = module[storeKey]?.getState();
module[storeKey]!.dispatch({
type: module[identifierKey],
method: key,
state: {
...lastState,
[module[identifierKey]!]: state,
},
_reactant: actionIdentifier,
...(module[enablePatchesKey]
? {
_patches: patches,
_inversePatches: inversePatches,
}
: {}),
});
},
});
});
module = {
[nameKey]: scheme.name,
[stateKey]: {
...scheme.state,
},
...scheme.actions,
};
return module as any;
}