diff --git a/src/index.ts b/src/index.ts index a567534..0bbbbbd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,9 +7,9 @@ export { apply } from './apply'; * Transactional updates to the base state with the recipe. */ export const mutate = (baseState: T, recipe: (state: T) => void) => { - const [, patches] = create(baseState, recipe, { + const [, patches, inversePatches] = create(baseState, recipe, { enablePatches: true, }); apply(baseState, patches); - return patches; + return { inversePatches, patches }; }; diff --git a/test/index.test.ts b/test/index.test.ts index 7a32636..464ab9e 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -1,4 +1,4 @@ -import { mutate } from '../src'; +import { mutate, apply } from '../src'; test('base - mutate', () => { const baseState = { @@ -6,10 +6,28 @@ test('base - mutate', () => { c: 1, }, }; - mutate(baseState, (draft) => { + const { patches, inversePatches } = mutate(baseState, (draft) => { draft.a.c = 2; }); expect(baseState).toEqual({ a: { c: 2 } }); + expect({ patches, inversePatches }).toEqual({ + patches: [ + { + op: 'replace', + path: ['a', 'c'], + value: 2, + }, + ], + inversePatches: [ + { + op: 'replace', + path: ['a', 'c'], + value: 1, + }, + ], + }); + apply(baseState, inversePatches); + expect(baseState).toEqual({ a: { c: 1 } }); }); test('base - mutate with error', () => {