immerjs / immer

Create the next immutable state by mutating the current one

Home Page:https://immerjs.github.io/immer/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is it ok to wrap state in object to allow reassign of all state tree?

832bb9 opened this issue Β· comments

πŸ™‹β€β™‚ Question

Immer docs says "Don't reassign the recipe argument", but there are cases where i want to apply some nested producer to whole tree and continue to modifying it. To allow it i created additional function which wraps whole state tree in object before passing it to actual produce function and extracts it from producer result.

const produceWrapped = <ValueT extends unknown>(
  recipe: (draft: Draft<{ value: ValueT }>) => void
) => (value: ValueT) => produce({ value }, recipe).value;

Works totally fine for me, but i am not sure if there are alternative approaches for it and is it totally fine from immer "philosophy" perspective.

Link to repro

https://codesandbox.io/s/weathered-surf-lkb6vv?file=/src/App.tsx

I think it is totally ok, u can also check this example.
https://codesandbox.io/s/limu-case2-ux70si?file=/src/App.tsx

Yes that is completely fine. Don't reassign literally refers to the draft = something else syntax. Not to reassigning an attribute of draft.