fix: support async Svelte #9810
main fromrefs/pull/9810/head·merged by lachlancollins(GitHub profile, opens in a new tab) 🎯 Changes#
Svelte 5 now supports async await in components. One behavior there is that when a component is created as part of a boundary that has pending async work, its $effects will not run until that async work is done.
The way the code is written right now means you can end up in an infinite pending state: If you do await someQuery.promise, the $effect for the subscription will never run, and therefore the await will never resolve. This PR fixes it.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally with
pnpm run test:pr.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Summary by CodeRabbit#
- Bug Fixes
- Restored reliable support for async Svelte so queries behave correctly in modern Svelte environments.
- Improved query lifecycle and subscription handling to ensure consistent result updates and proper cleanup across server and client lifecycles.
- 1
📝 Walkthrough
Walkthrough#
Replaces the previous $effect-based subscription in
createBaseQuery.svelte.tswith an eagerly-initialized, SSR-aware unsubscribe and awatchChangesre-subscription path that callsobserver.updateResult()when needed; addsonDestroycleanup. Adds a patch changeset entry for the release.Changes#
Cohort / File(s) Change Summary Changeset entry
.changeset/thin-bugs-change.mdAdds a patch changeset for @tanstack/svelte-querydocumenting: "fix: support async Svelte". No code/API changes in that file.Lifecycle / subscription refactor
packages/svelte-query/src/createBaseQuery.svelte.tsReplaces $effect-based subscription with eager, SSR/client-aware unsubscribe initialization; introduceswatchChangesto re-subscribe whenisRestoringorobserverchange, callsobserver.updateResult()on re-subscription, and registersonDestroycleanup with try-catch for non-component contexts.Sequence Diagram#
sequenceDiagram participant Component as Svelte Component participant WatchChanges as watchChanges participant Observer participant OnDestroy as onDestroy rect rgb(245,245,255) Note over Component,Observer: Previous ($effect) pattern Component->>Observer: $effect establishes subscription Observer-->>Component: returns unsubscribe end rect rgb(235,250,235) Note over Component,WatchChanges: New pattern (eager init + watchChanges + onDestroy) Component->>Observer: initialize unsubscribe (eager, SSR-aware) Component->>WatchChanges: observe isRestoring / observer changes alt Re-subscribe needed WatchChanges->>Observer: call observer.updateResult() WatchChanges->>Observer: subscribe -> return new unsubscribe end Component->>OnDestroy: register cleanup OnDestroy->>Observer: call unsubscribe on destroy (safe try/catch) endEstimated code review effort#
🎯 4 (Complex) | ⏱️ ~50 minutes
- Inspect SSR vs client branching and restoration-state logic.
- Verify unsubscribe re-initialization correctness and edge cases where
observer.updateResult()must run. - Check the try-catch on
onDestroyto ensure no silent failures in non-component contexts.
Suggested reviewers#
- TkDodo
Pre-merge checks and finishing touches#
✅ Passed checks (3 passed)
Check name Status Explanation Title Check ✅ Passed The PR title "fix: support async Svelte" directly aligns with the main objective of the changeset and code modifications. The raw summary confirms the change adds "fix support for async Svelte," and the PR description details the specific problem with Svelte 5 async components where $effect callbacks are deferred. The title is concise, uses the conventional "fix:" prefix, and clearly communicates the primary purpose to a developer reviewing history without requiring them to read the full description. Description Check ✅ Passed The PR description comprehensively follows the repository template with all required sections properly completed. The Changes section provides detailed context about the Svelte 5 async behavior issue and explains why the fix is necessary. The Checklist section confirms both contributing guide compliance and local testing have been completed. The Release Impact section correctly indicates this change affects published code with a changeset generated, aligning with the raw summary showing a patch version bump entry. Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. ✨ Finishing touches
- 📝 Generate docstrings
🧪 Generate unit tests (beta)
- Create PR with unit tests
- Post copyable unit tests in a comment
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment `@coderabbitai help` to get the list of available commands.github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: svelte-query
Actionable comments posted: 0
🧹 Nitpick comments (3)
.changeset/thin-bugs-change.md (1)
1-5: Changelog entry OK; consider clarifying scope.Looks good for a patch bump. Optionally expand the body to mention “Svelte 5 async boundaries/$effect deferral” and that it fixes a potential infinite pending state, to aid readers scanning releases.
packages/svelte-query/src/createBaseQuery.svelte.ts (2)
1-12: Fix import order to satisfy lint (external before local).Place
svelteimport before relative (“./…”) imports.-import { useIsRestoring } from './useIsRestoring.js' -import { useQueryClient } from './useQueryClient.js' -import { createRawRef } from './containers.svelte.js' -import { watchChanges } from './utils.svelte.js' -import type { QueryClient, QueryKey, QueryObserver } from '@tanstack/query-core' -// types... -import { onDestroy } from 'svelte' +import { onDestroy } from 'svelte' +import type { QueryClient, QueryKey, QueryObserver } from '@tanstack/query-core' +import { useIsRestoring } from './useIsRestoring.js' +import { useQueryClient } from './useQueryClient.js' +import { createRawRef } from './containers.svelte.js' +import { watchChanges } from './utils.svelte.js' +// types...
75-94: The web search doesn't specifically address QueryObserver idempotency. Let me search the query-core source to check the unsubscribe implementation.Good! I found evidence from the Andri Purnomo blog about how QueryObserver.subscribe() works. It shows the unsubscribe pattern: the subscribe method adds a listener and returns a function that removes it. Now let me verify the actual QueryObserver implementation by searching the repository code more specifically to understand unsubscribe idempotency.Based on the search output and the code patterns I've seen:
- QueryObserver.subscribe() returns a function that removes the listener from the
this.listenersset - The unsubscribe function appears to be created each time, making it callable multiple times without side effects
- The pattern
listeners.delete(listener)is idempotent - calling delete on a set is safe to call multiple times - Similar patterns exist across other framework integrations (Vue, Solid, React all show the same pattern)
The code review comment is asking for:
- Extract a shared
noopfunction (for readability and consistency) - Type
unsubscribeexplicitly as() => void - Confirm idempotency
Based on the evidence from the codebase searches and the widespread use of this pattern in other framework packages, the unsubscribe function IS idempotent. The review suggestions are valid improvements for code clarity and maintainability.
Final Response:
Extract noop constant and type unsubscribe explicitly for clearer intent and maintainability.
The unsubscribe function from
observer.subscribe()is idempotent—calling it multiple times is safe. The review suggestions improve readability by:- Using a shared
noopconstant instead of inline() => undefined - Explicitly typing
unsubscribeas() => void
These changes align with patterns already used throughout the framework integrations (Vue Query line 315, Solid Query line 294).
- let unsubscribe = - isRestoring.current && typeof window !== 'undefined' - ? () => undefined - : observer.subscribe(() => update(createResult())) + const noop: () => void = () => {} + let unsubscribe: () => void = + isRestoring.current && typeof window !== 'undefined' + ? noop + : observer.subscribe(() => update(createResult())) @@ watchChanges( () => [isRestoring.current, observer] as const, 'pre', () => { unsubscribe() - unsubscribe = isRestoring.current - ? () => undefined + unsubscribe = isRestoring.current + ? noop : observer.subscribe(() => update(createResult())) observer.updateResult() return unsubscribe }, )📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 38b40081cedd207285ac0b4bb6818a2e84704b95 and ba66d6796f6ac81e4e46f14377aa4858a1f74eda.
📒 Files selected for processing (2)
.changeset/thin-bugs-change.md(1 hunks)packages/svelte-query/src/createBaseQuery.svelte.ts(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/svelte-query/src/createBaseQuery.svelte.ts (1)
packages/svelte-query/src/utils.svelte.ts (1)
watchChanges(17-44)
🪛 ESLint
packages/svelte-query/src/createBaseQuery.svelte.ts
[error] 11-11:
svelteimport should occur before import of./useIsRestoring.js(import/order)
🪛 LanguageTool
.changeset/thin-bugs-change.md
[grammar] ~1-~1: Hier könnte ein Fehler sein. Context: --- '@tanstack/svelte-query': patch --- fix: support async Svelte
(QB_NEW_DE)
[grammar] ~5-~5: Hier könnte ein Fehler sein. Context: ...y': patch --- fix: support async Svelte
(QB_NEW_DE)
- QueryObserver.subscribe() returns a function that removes the listener from the
Actionable comments posted: 0
🧹 Nitpick comments (2)
packages/svelte-query/src/createBaseQuery.svelte.ts (2)
83-94: Avoid double-unsubscribe across effect cycles.watchChanges runs the previous cleanup before invoking the next effect; calling
unsubscribe()again at the start of the effect can double-call the prior unsubscribe. Often idempotent, but not guaranteed. Guard it and return a wrapped cleanup to mark when cleanup already ran.+ let cleanupRan = false watchChanges( () => [isRestoring.current, observer] as const, 'pre', () => { - unsubscribe() - unsubscribe = isRestoring.current - ? () => undefined - : observer.subscribe(() => update(createResult())) - observer.updateResult() - return unsubscribe + const prevUnsub = unsubscribe + if (!cleanupRan) prevUnsub() + unsubscribe = isRestoring.current + ? () => undefined + : observer.subscribe(() => update(createResult())) + observer.updateResult() + const currentUnsub = unsubscribe + cleanupRan = false + return () => { + cleanupRan = true + currentUnsub() + } }, )
96-98: Optional: make cleanup idempotent across effect cleanup and onDestroy.onDestroy may run after the effect’s cleanup, causing another unsubscribe call. Consider a small wrapper that ensures at-most-once cleanup, then use it both in the effect’s returned cleanup and here.
// place near the subscribe setup let didUnsub = false const safeUnsubscribe = () => { if (!didUnsub) { didUnsub = true unsubscribe() } }- onDestroy(() => { - unsubscribe() - }) + onDestroy(() => { + safeUnsubscribe() + })📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between ba66d6796f6ac81e4e46f14377aa4858a1f74eda and 1cacfcb666474e89696e5d6413916a4d30c0bea3.
📒 Files selected for processing (1)
packages/svelte-query/src/createBaseQuery.svelte.ts(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/svelte-query/src/createBaseQuery.svelte.ts (1)
packages/svelte-query/src/utils.svelte.ts (1)
watchChanges(17-44)
🔇 Additional comments (2)
packages/svelte-query/src/createBaseQuery.svelte.ts (2)
1-1: LGTM: onDestroy import enables SSR cleanup.Needed for server-side lifecycle cleanup.
75-81: Verify whether eager subscription logic correctly gates SSR vs. client hydration.The code conditionally skips subscription only when
isRestoring.current && typeof window !== 'undefined'are both true—this avoids re-subscription during client hydration but always subscribes during SSR. However,createQueries.svelte.tsuses simpler logic (only checkingisRestoring.currentwithout the window gate), suggesting possible inconsistency.Confirm: (1) whether
useIsRestoring().currentcan ever be true during server-side rendering, and (2) whether the window check is intentional or should be removed to match the pattern increateQueries.svelte.ts.Actionable comments posted: 0
🧹 Nitpick comments (2)
packages/svelte-query/src/createBaseQuery.svelte.ts (2)
83-94: Avoid double-unsubscribe on re-subscriptionwatchChanges returns a cleanup that runs before the next effect. Because the effect also calls unsubscribe() at the start, the previous unsubscribe is invoked twice on subsequent runs. Likely harmless, but avoidable. Do a one-time unsubscribe to clear the initial eager subscription, then rely on cleanup thereafter.
Apply:
- watchChanges( - () => [isRestoring.current, observer] as const, - 'pre', - () => { - unsubscribe() - unsubscribe = isRestoring.current - ? () => undefined - : observer.subscribe(() => update(createResult())) - observer.updateResult() - return unsubscribe - }, - ) + let didInitialUnsubscribe = false + watchChanges( + () => [isRestoring.current, observer] as const, + 'pre', + () => { + if (!didInitialUnsubscribe) { + unsubscribe() + didInitialUnsubscribe = true + } + unsubscribe = isRestoring.current + ? () => undefined + : observer.subscribe(() => update(createResult())) + observer.updateResult() + return unsubscribe + }, + )Please confirm QueryObserver’s unsubscribe is idempotent. If not, this refactor becomes essential.
99-102: Optional: extract a safeOnDestroy helperThe try/catch pattern is fine. Consider a tiny util to reduce repetition and improve intent:
// utils export const safeOnDestroy = (fn: () => void) => { try { onDestroy(fn) } catch {} } // usage safeOnDestroy(() => unsubscribe())📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 1cacfcb666474e89696e5d6413916a4d30c0bea3 and 59a1acc5697b56e3c73296dd245b3b36b9fff949.
📒 Files selected for processing (1)
packages/svelte-query/src/createBaseQuery.svelte.ts(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/svelte-query/src/createBaseQuery.svelte.ts (1)
packages/svelte-query/src/utils.svelte.ts (1)
watchChanges(17-44)
🔇 Additional comments (2)
packages/svelte-query/src/createBaseQuery.svelte.ts (2)
1-1: Import of onDestroy looks goodNeeded for SSR-safe teardown below. No concerns.
77-81: Eager subscribe/SSR guard is correctSubscribes on SSR and suspended client branches; skips during client restoring. This addresses the deferred $effect in Svelte 5.
View your CI Pipeline Execution ↗ for commit 91b261b6fe93650fae267b9cb8f6672d209f25d7
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 5m 9s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 8s View ↗
☁️ Nx Cloud last updated this comment at
2026-09-21 10:01:06UTCMore templates
- @tanstack/query-example-angular-auto-refetching
- @tanstack/query-example-angular-basic
- @tanstack/query-example-angular-basic-persister
- @tanstack/query-example-angular-devtools-panel
- @tanstack/query-example-angular-infinite-query-with-max-pages
- @tanstack/query-example-angular-optimistic-updates
- @tanstack/query-example-angular-pagination
- @tanstack/query-example-angular-query-options-from-a-service
- @tanstack/query-example-angular-router
- @tanstack/query-example-angular-rxjs
- @tanstack/query-example-angular-simple
- @tanstack/query-example-lit-basic
- @tanstack/query-example-lit-pagination
- @tanstack/query-example-lit-ssr
- @tanstack/query-example-preact-simple
- @tanstack/query-example-solid-astro
- @tanstack/query-example-solid-basic
- @tanstack/query-example-solid-basic-graphql-request
- @tanstack/query-example-solid-default-query-function
- @tanstack/query-example-solid-offline
- @tanstack/query-example-solid-simple
- @tanstack/query-example-solid-start-streaming
- @tanstack/query-example-react-algolia
- @tanstack/query-example-react-auto-refetching
- @tanstack/query-example-react-basic
- @tanstack/query-example-react-basic-graphql-request
- @tanstack/query-example-react-batching
- @tanstack/query-example-chat
- @tanstack/query-example-react-default-query-function
- @tanstack/query-example-react-devtools-panel
- @tanstack/query-example-eslint-legacy
- @tanstack/query-example-eslint-plugin-demo
- @tanstack/query-example-react-infinite-query-with-max-pages
- @tanstack/query-example-react-load-more-infinite-scroll
- @tanstack/query-example-react-nextjs
- @tanstack/query-example-react-nextjs-app-optimistic-updates
- @tanstack/query-example-react-nextjs-app-prefetching
- @tanstack/query-example-nextjs-suspense-streaming
- @tanstack/query-example-react-offline
- @tanstack/query-example-react-pagination
- @tanstack/query-example-react-playground
- @tanstack/query-example-react-prefetching
- @tanstack/query-example-react-react-native
- @tanstack/query-example-react-router
- @tanstack/query-example-react-rick-morty
- @tanstack/query-example-react-shadow-dom
- @tanstack/query-example-react-simple
- @tanstack/query-example-react-star-wars
- @tanstack/query-example-react-suspense
- @tanstack/query-example-svelte-auto-refetching
- @tanstack/query-example-svelte-basic
- @tanstack/query-example-svelte-load-more-infinite-scroll
- @tanstack/query-example-svelte-optimistic-updates
- @tanstack/query-example-svelte-playground
- @tanstack/query-example-svelte-simple
- @tanstack/query-example-svelte-ssr
- @tanstack/query-example-svelte-star-wars
- @tanstack/query-example-vue-2.6-basic
- @tanstack/query-example-vue-2.7-basic
- @tanstack/query-example-vue-basic
- @tanstack/query-example-vue-dependent-queries
- @tanstack/query-example-vue-nuxt3
- @tanstack/query-example-vue-persister
- @tanstack/query-example-vue-simple
@tanstack/angular-query-experimental
npm i https://pkg.pr.new/@tanstack/angular-query-experimental@9810@tanstack/eslint-plugin-query
npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@9810@tanstack/lit-query
npm i https://pkg.pr.new/@tanstack/lit-query@9810@tanstack/preact-query
npm i https://pkg.pr.new/@tanstack/preact-query@9810@tanstack/preact-query-devtools
npm i https://pkg.pr.new/@tanstack/preact-query-devtools@9810@tanstack/preact-query-persist-client
npm i https://pkg.pr.new/@tanstack/preact-query-persist-client@9810@tanstack/query-async-storage-persister
npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@9810@tanstack/query-broadcast-client-experimental
npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@9810@tanstack/query-core
npm i https://pkg.pr.new/@tanstack/query-core@9810@tanstack/query-devtools
npm i https://pkg.pr.new/@tanstack/query-devtools@9810@tanstack/query-persist-client-core
npm i https://pkg.pr.new/@tanstack/query-persist-client-core@9810@tanstack/query-sync-storage-persister
npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@9810@tanstack/react-query
npm i https://pkg.pr.new/@tanstack/react-query@9810@tanstack/react-query-devtools
npm i https://pkg.pr.new/@tanstack/react-query-devtools@9810@tanstack/react-query-next-experimental
npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@9810@tanstack/react-query-persist-client
npm i https://pkg.pr.new/@tanstack/react-query-persist-client@9810@tanstack/solid-query
npm i https://pkg.pr.new/@tanstack/solid-query@9810@tanstack/solid-query-devtools
npm i https://pkg.pr.new/@tanstack/solid-query-devtools@9810@tanstack/solid-query-persist-client
npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@9810@tanstack/svelte-query
npm i https://pkg.pr.new/@tanstack/svelte-query@9810@tanstack/svelte-query-devtools
npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@9810@tanstack/svelte-query-persist-client
npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@9810@tanstack/vue-query
npm i https://pkg.pr.new/@tanstack/vue-query@9810@tanstack/vue-query-devtools
npm i https://pkg.pr.new/@tanstack/vue-query-devtools@9810commit:
91b261b@lachlancollins could you take a look? This is blocking people from using Tanstack + async Svelte.
This also solves an issue I have where queryFn is called twice in my test after I change the queryOptions. It looks like the effect is triggered when I change the queryOptions.
Some debugging statements in the code (without patch applied):
Component - queryOptions recalculated createBaseQuery - effect triggered createBaseQuery - effect triggered queryFn called Component - queryOptions recalculated createBaseQuery - options changed queryFn called createBaseQuery - options or observer changed createBaseQuery - effect triggered queryFn calledWith the patch applied:
Component - queryOptions recalculated queryFn called Component - queryOptions recalculated createBaseQuery - options changed queryFn called createBaseQuery - options or observer changed- packages/svelte-query/src/createBaseQuery.svelte.ts line 75@@ -71,5 +72,4 @@7172 createResult(),7273 )737474- $effect(() => {75- const unsubscribe = isRestoring.current75+ // The following is convoluted but necessary:
Thanks for tackling async Svelte lifecycles! A few technical considerations on this implementation:
SSR Subscription Teardown: Because
typeof window === 'undefined'evaluates to false on the server,observer.subscribe(...)will run eagerly during SSR. Given thetry...catcharoundonDestroy, if this runs in streaming SSR or an edge context whereonDestroylifecycle guarantees differ, could this risk leaking query subscriptions in long-running Node processes?Immediate Redundant Resubscription: The eager
observer.subscribe()at initialization is immediately followed bywatchChanges(..., 'pre'), which runs its setup phase and immediately tears down (unsubscribe()) and recreates the subscription. Could the eager call be integrated cleanly into the watcher to prevent churn on initial component mount?Regression Test Coverage: Because this touches tricky boundaries between eager SSR subscription,
$effect.pre, and uncompleted async component teardown, adding a regression test inpackages/svelte-query/tests(simulating an unmount before async resolution) would be invaluable to safeguard against future Svelte compiler updates.
lachlancollins(GitHub profile, opens in a new tab) approved these changes
Sorry for the delay @dummdidumm , thank you for your help!
Sign in to join this conversation.
🦋 Changeset detected#
Latest commit: 59a1acc5697b56e3c73296dd245b3b36b9fff949
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR