Skip to content

Commit

Permalink
fix: make sure produceWithPatches accepts promises
Browse files Browse the repository at this point in the history
  • Loading branch information
cviejo authored Jan 11, 2022
1 parent e140918 commit d80e823
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
12 changes: 12 additions & 0 deletions __tests__/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -1728,6 +1728,18 @@ function runBaseTest(name, useProxies, autoFreeze, useListener) {
})
})
})

it("works with patches", () =>
produceWithPatches({a: 0}, async d => {
await Promise.resolve()
d.a = 1
}).then(([nextState, patches, inversePathes]) => {
expect(nextState).toEqual({a: 1})
expect(patches).toEqual([{op: "replace", path: ["a"], value: 1}])
expect(inversePathes).toEqual([
{op: "replace", path: ["a"], value: 0}
])
}))
})

it("throws when the draft is modified and another object is returned", () => {
Expand Down
8 changes: 6 additions & 2 deletions src/core/immerClass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,15 @@ export class Immer implements ProducersFns {
}

let patches: Patch[], inversePatches: Patch[]
const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {
const result = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {
patches = p
inversePatches = ip
})
return [nextState, patches!, inversePatches!]

if (typeof Promise !== "undefined" && result instanceof Promise) {
return result.then(nextState => [nextState, patches!, inversePatches!])
}
return [result, patches!, inversePatches!]
}

createDraft<T extends Objectish>(base: T): Draft<T> {
Expand Down

0 comments on commit d80e823

Please sign in to comment.