-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Description
Describe the bug
Hello tanstackers, we're using @tanstack/svelte-query with SvelteKit and followed the prefetching approach (ssr) as outlined here:
https://tanstack.com/query/latest/docs/framework/svelte/ssr#prefetching-data
We have a parent layout as in the docs:
import { browser } from '$app/environment'
import { QueryClient } from '@tanstack/svelte-query'
export async function load() {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
enabled: browser,
},
},
})
return { queryClient }
}
Everything seems to work fine, until we recently discovered that if we call SvelteKit's invalidateAll method (https://svelte.dev/docs/kit/$app-navigation#invalidateAll), the prefetched data is no longer available on mount.
This may sound confusing or expected (maybe?) but here's what we find problematic:
Expected behavior
The +page.svelte should immediately have access to the prefetched data from the cache. The createQuery should read from the cache that was populated by prefetchQuery as described in the docs:
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query'
// This data is cached by prefetchQuery in +page.ts so no fetch actually happens here
const query = createQuery(() => ({
queryKey: ['posts'],
queryFn: async () => (await fetch('/api/posts')).json(),
}))
</script>
Even after an invalidateAll someone would expect the prefetch data to be available as initial data so the client doesn't have to fetch/is not in a stale state effectively causing a client-side load.
src/routes/+page.ts
export async function load({ parent, fetch }) {
const { queryClient } = await parent()
// You need to use the SvelteKit fetch function here
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: async () => (await fetch('/api/posts')).json(),
})
}
Actual behavior
The query.data is empty/undefined for a split of a second after mount, and then the client refetches.
Again, this only happens after a SvelteKit invalidateAll call.
Reproduce
https://stackblitz.com/edit/sveltejs-kit-template-default-f4juyo11
Your minimal, reproducible example
https://stackblitz.com/edit/sveltejs-kit-template-default-f4juyo11
Steps to reproduce
Follow: https://stackblitz.com/edit/sveltejs-kit-template-default-f4juyo11
Expected behavior
query.data should have the prefetchQuery data on mount after the navigation
How often does this bug happen?
Every time
Screenshots or Videos
No response
Platform
MacOS, Chrome, SvelteKit
Tanstack Query adapter
svelte-query
TanStack Query version
6.0.17
TypeScript version
No response
Additional context
No response