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

fix(observe): solve the Ref not unwrapping on the ssr side issue with recursive way. #723

Merged
merged 3 commits into from Jul 2, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/reactivity/reactive.ts
Expand Up @@ -118,11 +118,30 @@ export function observe<T>(obj: T): T {
// in SSR, there is no __ob__. Mock for reactivity check
if (!hasOwn(observed, '__ob__')) {
def(observed, '__ob__', mockObserver(observed))
walk(observed)
}

return observed
}

/**
* Recursive obj, add __ob__
*/
function walk(obj: any) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
function walk(obj: any) {
function walk(obj: any, seen = new WeakMap<any, boolean>()) {

Would need a map to avoid circular reference.

var keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
if (
!(isPlainObject(obj[keys[i]]) || isArray(obj[keys[i]])) ||
isRaw(obj[keys[i]]) ||
!Object.isExtensible(obj[keys[i]])
) {
continue
}
def(obj[keys[i]], '__ob__', mockObserver(obj[keys[i]]))
walk(obj[keys[i]])
}
}

export function createObserver() {
return observe<any>({}).__ob__
}
Expand Down
3 changes: 1 addition & 2 deletions src/reactivity/set.ts
Expand Up @@ -40,8 +40,7 @@ export function set<T>(target: any, key: any, val: T): T {
return val
}
if (!ob) {
// If we are using `set` we can assume that the unwrapping is intended
defineAccessControl(target, key, val)
target[key] = val
return val
}
defineReactive(ob.value, key, val)
Expand Down
16 changes: 16 additions & 0 deletions test/ssr/ssrReactive.spec.ts
Expand Up @@ -102,4 +102,20 @@ describe('SSR Reactive', () => {
new: true,
})
})

// #721
it('should behave correctly for the nested ref in the object', () => {
const state = { old: ref(false) }
set(state, 'new', ref(true))
expect(JSON.stringify(state)).toBe(
'{"old":{"value":false},"new":{"value":true}}'
)
})

// #721
it('should behave correctly for ref of object', () => {
const state = ref({ old: ref(false) })
set(state.value, 'new', ref(true))
expect(JSON.stringify(state.value)).toBe('{"old":false,"new":true}')
})
})