Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: mutation of an object that is not a part of the draft #76

Open
prodderman opened this issue Jan 21, 2025 · 2 comments
Open

Question: mutation of an object that is not a part of the draft #76

prodderman opened this issue Jan 21, 2025 · 2 comments

Comments

@prodderman
Copy link

Hello!

Is there a way to avoid mutation of the object that is not a part of the draft? (except deepCopy)

const defaultPart = {
    y: 1,
};

const state = {
  x: undefined
};

const newState = create(state, draftState => {
  stateDraft.x ??= defaultPart;
  stateDraft.x.y = 2; // mutates original object
})

console.log(defaultPart.y) // 2

I tried to create draft inside but it doesn't finalize

...
const newState = create(state, draftState => {
  stateDraft.x ??= create(defaultPart)[0];
  stateDraft.x.y = 2;
})

console.log(newState.x) // Proxy(Object) { ... }
@unadlib
Copy link
Owner

unadlib commented Jan 22, 2025

hi @prodderman , Mutative does not support finalizing drafts across multiple scopes draft.

Perhaps you can use it like this,

const defaultPart = {
  y: 1,
};

const state = {
  x: undefined,
};

const newState = create(state, (draftState) => {
  const [subDraft, finalize] = create(defaultPart);
  subDraft.y = 2;
  const state = finalize();
  draftState.x ??= state;
});

console.log(newState.x); // { y: 2 }
console.log(defaultPart.y); // 1

@unadlib
Copy link
Owner

unadlib commented Jan 22, 2025

You can also use it like this.

const defaultPart = {
  y: 1,
};

const state = {
  x: undefined,
};

let [stateDraft, finalize] = create(state);
stateDraft.x ??= defaultPart;
[stateDraft, finalize] = create(finalize());
stateDraft.x.y = 2;
const newState = finalize();

console.log(newState.x); // { y: 2 }
console.log(defaultPart.y); // 1

You must ensure that the correspondence between the immutable tree and the draft is maintained.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants