T
TanStack3y ago
correct-apricot

SSR + SvelteKit w/prefetching data should only fetch during the prefetch and not client-side

The expected behavior is that there isn't an initial fetch on the client.
From the provided SSR example (https://tanstack.com/query/latest/docs/svelte/examples/svelte/ssr), it seems that there are two fetches occurring (one for the prefetch and one on the client) when I observe the events in the network tab in the screenshot (i.e. after hitting the browser refresh button for the CodeSandbox). Am I misinterpreting the intended behavior/implementation of this feature? Edit: the expected behavior is that the data is present on the page prior to any client-side fetches; and additional fetches are done in the background to update the state
Svelte Query Ssr), Example | TanStack Query Docs
An example showing how to implement Ssr), in Svelte Query
No description
4 Replies
harsh-harlequin
harsh-harlequin3y ago
If you set staleTime to high enough value, like 3 seconds, the second fetch would not happen. By default all queries are considered stale immediately after fetch. So by the time it reaches the browser, client thinks that it should refetch.
correct-apricot
correct-apricotOP3y ago
SSR | TanStack Query Docs
React Query supports two ways of prefetching data on the server and passing that to the queryClient. Prefetch the data yourself and pass it in as initialData
correct-apricot
correct-apricotOP3y ago
If I edit the function signature in src/lib/data.ts to accept an optional load fetch (i.e. to override the global fetch):
import type { LoadEvent } from "@sveltejs/kit";
export const getPosts = async (limit: number, loadFetch?: LoadEvent["fetch"])
import type { LoadEvent } from "@sveltejs/kit";
export const getPosts = async (limit: number, loadFetch?: LoadEvent["fetch"])
and then pass it as an argument to the queryFn for prefetching in src/routes/+page.ts, then I only see 1 request for posts when I refresh the page https://codesandbox.io/s/zen-dijkstra-wqm5p8?file=/src/lib/data.ts
bevm0
CodeSandbox
zen-dijkstra-wqm5p8 - CodeSandbox
zen-dijkstra-wqm5p8 by bevm0 using @tanstack/svelte-query
correct-apricot
correct-apricotOP3y ago
This seems to follow my initial expectation that there would only be 1 request, even though I didn't modify the staleTime

Did you find this page helpful?