This might not be a bug, but I don't know how else to report it.
Please check this stackoverflow question:
Immer only copies objects that were drafted and then modified.
In your example, you'll need to clone somArrayUpdate manually.
Thank you for the immediate feedback!
I am sorry to insist but doesn't this defeat the purpose of immer?
I mean, I am using immer to avoid spread operators, cloning etc.
But in the case where I want to completely replace an object/array I have to remember that if I need to clone the object/array first?
Also, is this documented somewhere on the README?
The only goal of Immer is to copy any modified branches of the state tree you pass into produce.
@mweststrate can convince you why that's the right approach, if he wants. :)
@atrifyllis immer doesn't impact your program outside produce functions, where just the normal javascript rules apply. So to benefit from immer, your mutations have to happen inside produce. What happens outside of that has nothing to do with immer.
The fact that you treat somArrayUpdate as a mutable data structure is entirely up to you, and not something immer can or tries to prevent. The draft.someArray pointer is modified, so you will get a copy of draft with an updated field as result. But what someArray is pointing to, and whether that thing is immutable or not, is outside the scope of immer. That could be even an object like window. Anything in draft that is touched inside a producer will be frozen in dev mode. But the rest of the world is outside immers scope.
@mweststrate I understand that now, but do you think this is obvious from the documentation?
TBH, I would expect that I get a deep copy of draft, which means a deep copy of my array so I do not have to deal with pointer issues.
If you want a deep copy, just pick a lodash utility. The whole point of immer is to _not_ produce deep copies, but rather structurally shared data structures, which are much, much more efficient, creation, computation and memory wise.
Most helpful comment
If you want a deep copy, just pick a lodash utility. The whole point of immer is to _not_ produce deep copies, but rather structurally shared data structures, which are much, much more efficient, creation, computation and memory wise.