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/thin-bugs-change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/svelte-query': patch
---

fix: support async Svelte
32 changes: 27 additions & 5 deletions packages/svelte-query/src/createBaseQuery.svelte.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { onDestroy } from 'svelte'
import { useIsRestoring } from './useIsRestoring.js'
import { useQueryClient } from './useQueryClient.js'
import { createRawRef } from './containers.svelte.js'
Expand Down Expand Up @@ -71,13 +72,34 @@ export function createBaseQuery<
createResult(),
)

$effect(() => {
const unsubscribe = isRestoring.current
// The following is convoluted but necessary:
// Call eagerly so subscription happens on the server and on suspended branches in the client...
let unsubscribe =
isRestoring.current && typeof window !== 'undefined'
? () => undefined
: observer.subscribe(() => update(createResult()))
observer.updateResult()
return unsubscribe
})
// ...but also watch for state changes to resubscribe, and because Svelte right now doesn't
// run onDestroy on components with pending work that are destroyed again before they are resolved...
watchChanges(
() => [isRestoring.current, observer] as const,
'pre',
() => {
unsubscribe()
unsubscribe = isRestoring.current
? () => undefined
: observer.subscribe(() => update(createResult()))
observer.updateResult()
return unsubscribe
},
)
// ...and finally also cleanup via onDestroy because that one runs on the server whereas $effect.pre does not.
// (in a try-catch because it theoretically can be called in a non-component context - that should not happen
// but it would be a breaking change technically to error out here. SSR-safe because this wouldn't be called during SSR if it was not in a component)
try {
onDestroy(() => {
unsubscribe()
})
} catch (e) {}

watchChanges(
() => resolvedOptions,
Expand Down
Loading