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(vanilla): revert #970 #986

Merged
merged 4 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/vanilla.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,10 @@ const createSnapshotDefault = <T extends object>(
if (refSet.has(value as object)) {
markToTrack(value as object, false) // mark not to track
} else if (proxyStateMap.has(value as object)) {
const [target] = proxyStateMap.get(value as object) as ProxyState
desc.value = createSnapshotDefault(target, version) as Snapshot<T>
const [target, ensureVersion] = proxyStateMap.get(
value as object,
) as ProxyState
desc.value = createSnapshotDefault(target, ensureVersion()) as Snapshot<T>
}
Object.defineProperty(snap, key, desc)
})
Expand Down
32 changes: 32 additions & 0 deletions tests/basic.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -497,3 +497,35 @@ it('respects property enumerability (#726)', async () => {
const x = proxy(Object.defineProperty({ a: 1 }, 'b', { value: 2 }))
expect(Object.keys(snapshot(x))).toEqual(Object.keys(x))
})

it('stable snapshot object (#985)', async () => {
const state = proxy({ count: 0, obj: {} })

let effectCount = 0

const TestComponent = () => {
const { count, obj } = useSnapshot(state)
useEffect(() => {
++effectCount
}, [obj])
return (
<>
<div>count: {count}</div>
<button onClick={() => ++state.count}>button</button>
</>
)
}

const { getByText, findByText } = render(<TestComponent />)

await findByText('count: 0')
expect(effectCount).toBe(1)

fireEvent.click(getByText('button'))
await findByText('count: 1')
expect(effectCount).toBe(1)

fireEvent.click(getByText('button'))
await findByText('count: 2')
expect(effectCount).toBe(1)
})
10 changes: 9 additions & 1 deletion tests/snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,15 @@ it('should not change snapshot with modifying the original proxy', async () => {
expect(snap2.obj2.nested.count).toBe(2)
})

describe('snapsoht typings', () => {
it('should return stable nested snapshot object', async () => {
const state = proxy({ count: 0, obj: {} })
const snap1 = snapshot(state)
state.count++
const snap2 = snapshot(state)
expect(snap2.obj).toBe(snap1.obj)
})

describe('snapshot typings', () => {
it('converts object properties to readonly', () => {
expectType<
TypeEqual<
Expand Down