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

Can immer.js can be used for future mutations?

Amansaxena001 opened this issue Β· comments

πŸ™‹β€β™‚ Question

Imagine a class designed with properties and methods where the methods are essentially getters, returning the properties of the class. As this class serves as a utility across the codebase, using its methods to access properties can inadvertently lead to mutating the original properties due to returning the same reference. This unintended mutation can cause issues.

To prevent such problems, I'm exploring mechanisms to safeguard against accidental mutations. While Immer provides a solution for managing mutations, it might not be suitable for this scenario where mutations occur in the future without knowing what changes will be made, unlike Immer where changes are predefined.

class CommonPkg {
  state = {
    a: 1,
    b: [2, 3],
    c: {
      d: {
        f: 8
      }
    }
  };

  getState() {
    return this.state;
  }
... rest getters

}

const init=new CommonPkg();

const utils={
    getState:init.getState
}

// somewhere else in the code by importing the utils
const data=utils.getState();

// this is the problem
data.a = 2

Link to repro

Please provide a CodeSandbox demo to clarify your question if possible. Typically, questions without minimal codesandbox demo won't be answered.

Environment

We only accept questions against the latest Immer version.

  • Immer version:
  • Occurs with setUseProxies(true)
  • Occurs with setUseProxies(false) (ES5 only)

Sorry, I tried reading three times, but I'm still puzzled about what the problem or the question isπŸ˜…

@mweststrate I ve rephrased it let me know if you are still not able to understand the question and also refer the code example too to understand the problem.

@mweststrate nvm, this is resolved now and thanks anyway.
Marking this closed.