From 12b8ce963e4dd0743a756a91f7897b9066ee5621 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A9ry=20Debongnie?= Date: Tue, 15 Feb 2022 16:37:03 +0100 Subject: [PATCH] [IMP] reactivity: toRaw now works with non reactive objects --- doc/reference/reactivity.md | 7 +++++++ src/reactivity.ts | 2 +- tests/reactivity.test.ts | 5 +++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/doc/reference/reactivity.md b/doc/reference/reactivity.md index 5e799668..edba83ee 100644 --- a/doc/reference/reactivity.md +++ b/doc/reference/reactivity.md @@ -117,3 +117,10 @@ rawState.value = 3; // will NOT be picked up by the reactivity system!!! Here again, this is useful in some situations where we want to explicitely bypass Owl, but using this function means that the responsability of coordinating state update is given to the user code, instead of Owl. Subtle bugs may arise! + +Also, normal (non-reactive objects) will be directly returned by `toRaw`: + +```js +const obj = { a: 1 }; +console.log(toRaw(obj) === obj); // true +``` diff --git a/src/reactivity.ts b/src/reactivity.ts index 40053ca4..2a49fadf 100644 --- a/src/reactivity.ts +++ b/src/reactivity.ts @@ -57,7 +57,7 @@ export function markRaw(value: T): NonReactive { * @returns the underlying value */ export function toRaw(value: Reactive): T { - return value[TARGET]; + return value[TARGET] || value; } const targetToKeysToCallbacks = new WeakMap>>(); diff --git a/tests/reactivity.test.ts b/tests/reactivity.test.ts index 35b1e453..8f1328f9 100644 --- a/tests/reactivity.test.ts +++ b/tests/reactivity.test.ts @@ -1131,6 +1131,11 @@ describe("toRaw", () => { expect(reactiveObj).not.toBe(obj); expect(toRaw(reactiveObj as Reactive)).toBe(obj); }); + + test("giving a non reactive to toRaw return the object itself", () => { + const obj = { value: 1 }; + expect(toRaw(obj as Reactive)).toBe(obj); + }); }); describe("Reactivity: useState", () => {