Skip to content
Myr

feat: introduced produceWithPatches. Implements #400

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Michel Weststrate · committed by Michel Weststrate · parent 615ca6f · Browse files · 6 files+166 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+166 added−2 removed

  • tests:+60 added−2 removed
  • other:+106 added−0 removed

6 files+166 added−2 removed

modified:__tests__/curry.js+25 added-1 removed
modified:__tests__/readme.js+35 added-1 removed
1"use strict"2import produce, {applyPatches, immerable} from "../src/index"2import produce, {3 applyPatches,4 immerable,5 produceWithPatches6} from "../src/index"78describe("readme example", () => {9 it("works", () => {10 const baseState = [
160 unmodified lines
171 expect(diner).not.toBe(lunch)172 expect(lunch).toBeInstanceOf(Clock)173 expect(diner.toString()).toBe("18:30")174 })175176 test("produceWithPatches", () => {177 const result = produceWithPatches(178 {179 age: 33180 },181 draft => {182 draft.age++183 }184 )185 expect(result).toEqual([186 {187 age: 34188 },189 [190 {191 op: "replace",192 path: ["age"],193 value: 34194 }195 ],196 [197 {198 op: "replace",199 path: ["age"],200 value: 33201 }202 ]203 ])204 })205})
modified:src/immer.d.ts+43 added
107 unmodified lines
108109export const produce: IProduce110export default produce111112/**113 * Like `produce`, but instead of just returning the new state,114 * a tuple is returned with [nextState, patches, inversePatches]115 *116 * Like produce, this function supports currying117 */118export interface IProduceWithPatches {119 /** Curried producer */120 <121 Recipe extends (...args: any[]) => any,122 Params extends any[] = Parameters<Recipe>,123 T = Params[0]124 >(125 recipe: Recipe126 ): <Base extends Immutable<T>>(127 base: Base,128 ...rest: Tail<Params>129 ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]130 // ^ by making the returned type generic, the actual type of the passed in object is preferred131 // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe132 // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!133134 /** Curried producer with initial state */135 <136 Recipe extends (...args: any[]) => any,137 Params extends any[] = Parameters<Recipe>,138 T = Params[0]139 >(140 recipe: Recipe,141 initialState: Immutable<T>142 ): <Base extends Immutable<T>>(143 base?: Base,144 ...rest: Tail<Params>145 ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]146147 /** Normal producer */148 <Base, D = Draft<Base>, Return = void>(149 base: Base,150 recipe: (draft: D) => Return151 ): [Produced<Base, Return>, Patch[], Patch[]]152}153export const produceWithPatches: IProduceWithPatches154155/** Use a class type for `nothing` so its type is unique */156declare class Nothing {157 // This lets us do `Exclude<T, Nothing>`158 private _: any
133 unmodified lines
modified:src/immer.js+16 added
89 unmodified lines
90 if (result === undefined) return base91 return result !== NOTHING ? result : undefined92 }93 }94 produceWithPatches(arg1, arg2, arg3) {95 if (typeof arg1 === "function") {96 const self = this97 return (state, ...args) =>98 this.produceWithPatches(state, draft => arg1(draft, ...args))99 }100 // non-curried form101 if (arg3)102 throw new Error("A patch listener cannot be passed to produceWithPatches")103 let patches, inversePatches104 const nextState = this.produce(arg1, arg2, (p, ip) => {105 patches = p106 inversePatches = ip107 })108 return [nextState, patches, inversePatches]109 }110 createDraft(base) {111 if (!isDraftable(base)) {112 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore113 }
199 unmodified lines
modified:src/index.js+6 added
modified:readme.md+41 added
331 unmodified lines
332 {"op": "add", "path": ["tags", 3], "value": "kiddo"}333]334```335336### `produceWithPatches`337338Instead of setting up a patch listener, an easier way to obtain the patches is to use `produceWithPatches`, which has the same signature as `produce`, except that it doesn't return just the next state, but a tuple consisting of `[nextState, patches, inversePatches]`. Like `produce`, `produceWithPatches` supports currying as well.339340```javascript341import {produceWithPatches} from "immer"342343const [nextState, patches, inversePatches] = produceWithPatches(344 {345 age: 33346 },347 draft => {348 draft.age++349 }350)351```352353Which produces:354355```javascript356;[357 {358 age: 34359 },360 [361 {362 op: "replace",363 path: ["age"],364 value: 34365 }366 ],367 [368 {369 op: "replace",370 path: ["age"],371 value: 33372 }373 ]374]375```376377For a more in-depth study, see [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)378379Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.380
453 unmodified lines