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

finishDraft should have an option to not freeze the resulting object

wighawag opened this issue Β· comments

πŸš€ Feature Proposal

finishDraft should have an option to not freeze the resulting object

Motivation

I am using immer only sometime and because of that I currently need to call setAutoFreeze this is unfortunately a global operation and this prevent me from using autofreeze in other places I use immer without also calling setAutoFreeze there at every place I need it.

My use of immer is as follow

I got a state

const wrapper = {
  state
}

I received data, that data is used to change the state

that data is sometime know to be non-reversible and for efficiency I just modify state

But in some other case, that data might need to be reversed so I create a draft and apply the changes keeping track of patches

const draft = createDraft(wrapper.state)

const finalizedDraft = finishDraft(
  draft
 (_, reversePatches) => {
   // leep track of patches
});

wrapper.state = finalizedDraft;

The last line freeze the state

and this prevent me from using raw state afterward even though the new data could be known to be reversible

Can this be solved in user-land code?

Not really as setAutoFreeze is global and switching back just before finishDraft is not elegant

Example

finishDraft(draft, (_, reversePatches) => {}, {autofreeze: false})

Actually, just after posting this I discovered we can instantiate Immer instance and have autofreeze local to it

const immer = new Immer({autoFreeze: false});
immer.createDraft()
...

I still feel like having freeze as an option to finishDraft is more elegant

Agreed it would be slightly more elegant, but for simplicity sake and not having too many ways to achieve the same thing, I propose to keep it as is. A short-hand utility around this is quickly written in user land code.