immer icon indicating copy to clipboard operation
immer copied to clipboard

Reassigning to the same Date object generates new copy with empty patches

Open somebody32 opened this issue 4 years ago • 2 comments

🐛 Bug Report

If you mutate Date property inside produce but then revert it, immer still assumes changes while returning an empty set of patches.

Link to repro

https://codesandbox.io/s/immer-reassigning-breaks-immutabillity-2u7ob


import {enablePatches, produceWithPatches} from "immer"

enablePatches();

type DataObject = { 
  date: Date;
}

let initialDate = new Date();
let data: DataObject[] = [{date: initialDate}];

let [newData, patches] = produceWithPatches(data, draft => {
  let element = draft[0];
  let dateBefore = element.date;
 
  element.date = new Date()
  element.date = dateBefore;
});

console.log("Patches:", patches) // []
console.log("New Date equal to Initial", newData[0].date === initialDate) // true
console.log("Array equal", newData === data); // expect true but getting false

Environment

Immer version: 9.0.6

  • [x] I filed this report against the latest version of Immer
  • [x] Occurs with setUseProxies(true)
  • [x] Occurs with setUseProxies(false) (ES5 only)

somebody32 avatar Oct 15 '21 12:10 somebody32

I looked more deeply into the issue, and in reality, it is not a bug, but more a current limitation of immer. And it happens with any primitive, not only objects. So I think it can be treated more like a feature request.

Also, is there anything architecturally limiting from achieving this? As far as I can tell, setter that now sets _modified can also reset that flag if the original value was passed again, or am I wrong?

somebody32 avatar Oct 19 '21 14:10 somebody32

I think that analysis is correct, it could detect the same value is assigned and keep the result. Feel free to attempt a PR

mweststrate avatar Jan 11 '22 13:01 mweststrate