Skip to content

Commit

Permalink
fix(draft): fix draft final update value issue
Browse files Browse the repository at this point in the history
  • Loading branch information
unadlib committed Nov 9, 2023
1 parent f968d85 commit d480a46
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 17 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mutative",
"version": "0.7.0",
"version": "0.7.1",
"description": "A JavaScript library for efficient immutable updates",
"main": "dist/index.js",
"module": "dist/mutative.esm.js",
Expand Down
16 changes: 0 additions & 16 deletions src/draft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,22 +260,6 @@ export function createDraft<T extends object>(createDraftOptions: {
target.options.updatedValues ?? new WeakMap();
target.options.updatedValues.set(updatedValue, proxyDraft.original);
}
if (
proxyDraft.parent!.key !== undefined &&
proxyDraft.parent!.parent!.proxy
) {
const parent =
proxyDraft.parent!.parent!.proxy[proxyDraft.parent!.key];
const parentProxyDraft = getProxyDraft(parent);
if (parentProxyDraft === undefined) {
// !case: handle assigning a non-draft with the same key
copy = parent;
const current = get(copy, key!);
if (!getProxyDraft(current)) {
updatedValue = current;
}
}
}
// final update value
set(copy, key!, updatedValue);
}
Expand Down
62 changes: 62 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3297,3 +3297,65 @@ test('#18: assigning a non-draft with the different key - enablePatches', () =>
expect(apply(baseState, created[1])).toEqual(created[0]);
expect(apply(created[0], created[2])).toEqual(baseState);
});

test('array: assigning a non-draft array', () => {
const baseState = {
data: [{ a: true }],
};

const state = create(baseState, (draft) => {
const a = draft.data.filter((item) => item.a);
// @ts-ignore
draft.data = [];
});

expect(state.data.length).toBe(0);
});

test('object: assigning a non-draft array', () => {
const baseState = {
data: { a: { b: true } },
};

const state = create(baseState, (draft) => {
Object.values(draft.data).forEach((item) => {
item.b = false;
});
// @ts-ignore
draft.data = {};
});

expect(Object.values(state.data).length).toBe(0);
});

test('set: assigning a non-draft array', () => {
const baseState = {
data: new Set([{ b: true }]),
};

const state = create(baseState, (draft) => {
draft.data.forEach((item) => {
//
});
// @ts-ignore
draft.data = new Set();
});

expect(state.data.size).toBe(0);
});

test('map: assigning a non-draft array', () => {
const baseState = {
data: new Map([[0, { b: true }]]),
};

const state = create(baseState, (draft) => {
draft.data.forEach((item) => {
//
});
// @ts-ignore
draft.data = new Map();
});

expect(state.data.size).toBe(0);
});

0 comments on commit d480a46

Please sign in to comment.