Classes
Plain objects (objects without a prototype), arrays, Map
s and Set
s are always drafted by Immer. Every other object must use the immerable
symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.
#
Example#
Semantics in detailThe semantics on how classes are drafted are as follows:
- A draft of a class is a fresh object but with the same prototype as the original object.
- When creating a draft, Immer will copy all own properties from the base to the draft.This includes non-enumerable and symbolic properties.
- Own getters will be invoked during the copy process, just like
Object.assign
would. - Inherited getters and methods will remain as is and be inherited by the draft.
- Immer will not invoke constructor functions.
- The final instance will be constructed with the same mechanism as the draft was created.
- Only getters that have a setter as well will be writable in the draft, as otherwise the value can't be copied back.
Because Immer will dereference own getters of objects into normal properties, it is possible to use objects that use getter/setter traps on their fields, like MobX and Vue do.
Immer does not support exotic / engine native objects such as DOM Nodes or Buffers, nor is subclassing Map, Set or arrays supported and the immerable
symbol can't be used on them.
So when working for example with Date
objects, you should always create a new Date
instance instead of mutating an existing Date
object.