Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/nullable-collection-getter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/svelte-db': patch
---

Fix nullable collection getters in useLiveQuery causing errors during SSR
3 changes: 3 additions & 0 deletions packages/svelte-db/src/useLiveQuery.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,9 @@ export function useLiveQuery(
startSync: true,
})
} else {
if (unwrappedParam === null || unwrappedParam === undefined) {
return null
}
return createLiveQueryCollection({
...unwrappedParam,
startSync: true,
Expand Down
49 changes: 49 additions & 0 deletions packages/svelte-db/tests/useLiveQuery.svelte.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -837,6 +837,55 @@ describe(`Query Collections`, () => {
})
})

it(`should handle nullable collection getter returning null`, () => {
const collection = createCollection(
mockSyncCollectionOptions<Person>({
id: `nullable-getter-test`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)

cleanup = $effect.root(() => {
// Create a live query collection
const liveQueryCollection = createLiveQueryCollection({
query: (q) =>
q
.from({ persons: collection })
.where(({ persons }) => gt(persons.age, 30))
.select(({ persons }) => ({
id: persons.id,
name: persons.name,
})),
startSync: true,
})

// Simulate SSR scenario: collection getter initially returns null
let currentCollection = $state<typeof liveQueryCollection | null>(null)

// This should not throw when the getter returns null
const queryResult = useLiveQuery(() => currentCollection)

flushSync()

// When collection is null, should return empty/idle state
expect(queryResult.state.size).toBe(0)
expect(queryResult.data).toEqual([])

// Now set the actual collection
currentCollection = liveQueryCollection

flushSync()

// Should now have data from the collection
expect(queryResult.state.size).toBe(1)
expect(queryResult.state.get(`3`)).toMatchObject({
id: `3`,
name: `John Smith`,
})
})
})

describe(`isReady property`, () => {
it(`should be false initially and true after collection is ready`, () => {
let beginFn: (() => void) | undefined
Expand Down
Loading