Skip to content

fix(svelte-query): fix error when creating query outside of component #9222

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

Open
wants to merge 1 commit into
base: svelte-5-adapter
Choose a base branch
from
Open
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
fix(svelte-query): fix error when creating query outside of component…
… initialization

Add $effect.root to allow creating queries in event handlers. Previously creating a query outside of component initialization would throw an effect_orphan error
  • Loading branch information
arnolicious committed May 30, 2025
commit 22b08436113a8e23fb44d9574bff4434cb152100
43 changes: 23 additions & 20 deletions packages/svelte-query/src/createBaseQuery.svelte.ts
Original file line number Diff line number Diff line change
@@ -57,26 +57,29 @@ export function createBaseQuery<
createResult(),
)

$effect(() => {
const unsubscribe = isRestoring.current
? () => undefined
: observer.subscribe(() => update(createResult()))
observer.updateResult()
return unsubscribe
})

$effect.pre(() => {
observer.setOptions(resolvedOptions)
// The only reason this is necessary is because of `isRestoring`.
// Because we don't subscribe while restoring, the following can occur:
// - `isRestoring` is true
// - `isRestoring` becomes false
// - `observer.subscribe` and `observer.updateResult` is called in the above effect,
// but the subsequent `fetch` has already completed
// - `result` misses the intermediate restored-but-not-fetched state
//
// this could technically be its own effect but that doesn't seem necessary
update(createResult())
// Avoid effect_orphan error when creating a query inside an event handler instead of during component initialization
$effect.root(() => {
$effect(() => {
const unsubscribe = isRestoring.current
? () => undefined
: observer.subscribe(() => update(createResult()))
observer.updateResult()
return unsubscribe
})

$effect.pre(() => {
observer.setOptions(resolvedOptions)
// The only reason this is necessary is because of `isRestoring`.
// Because we don't subscribe while restoring, the following can occur:
// - `isRestoring` is true
// - `isRestoring` becomes false
// - `observer.subscribe` and `observer.updateResult` is called in the above effect,
// but the subsequent `fetch` has already completed
// - `result` misses the intermediate restored-but-not-fetched state
//
// this could technically be its own effect but that doesn't seem necessary
update(createResult())
})
})

return query