immerjs / immer

Create the next immutable state by mutating the current one
https://immerjs.github.io/immer/
MIT License
27.5k stars 850 forks source link

Can immer.js can be used for future mutations? #1121

Closed Amansaxena001 closed 4 months ago

Amansaxena001 commented 4 months ago

πŸ™‹β€β™‚ 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.

mweststrate commented 4 months ago

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

Amansaxena001 commented 4 months ago

@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.

Amansaxena001 commented 4 months ago

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