Build Vue's proxy variants: readonly, shallowReactive, shallowRef with triggerRef, markRaw, toRaw and ref unwrapping
Problem
reactive() and ref() are the default, but real Vue apps lean on the variants: readonly for state a child must not change, shallowRef for a large list you replace rather than mutate, markRaw for a chart instance or SDK client that must never be proxied, and toRaw to hand plain data to a library. Most of them are the same Proxy with two flags. Build them on the small tracking core in the starter.
const view = readonly(reactive({ count: 1 }));
effect(() => console.log(view.count)); // 1
toRaw(view).count; // 1, the original object
view.count = 5; // ignored
const rows = shallowRef([1, 2]);
rows.value.push(3); // nothing re-runs
triggerRef(rows); // effects that read rows.value re-runRef. UR-1461 · © UIRound · uiround.com/questions/build-vues-proxy-variants-readonly-shallowreactive-shallowref-with-triggerref-markraw-toraw-and-ref-unwrapping
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 3
- code listings
- 8
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Write one factory,
createReactiveObject(target, isReadonly, isShallow, cache), and onegethandler that takes the two flags. The four public functions only pick flags and a WeakMap cache. Answer__v_isReactive,__v_isReadonly,__v_isShallowand__v_rawinsideget.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.