examples/svelte/prefetching-sveltekit
| Name | Last commit message | Last commit date |
|---|---|---|
| .. | ||
README.md
TanStack Svelte Query Prefetching Example (SvelteKit)#
Prefetches a character when you hover its link, so the detail view opens without a loading state.
Built with SvelteKit.
How it works#
src/lib/services/characters/queries.tsdefinescharactersQueries.list()andcharactersQueries.detail(id)withqueryOptions. The detail options useskipTokenwhen there is noid.src/lib/services/characters/api.tsfetches characters from the Rick and Morty API after a 500 ms delay.src/lib/CharacterItem.sveltecallsqueryClient.query(...)with a 10-secondstaleTimeonmouseenterandfocusin, so a character is fetched again only when its cached data is older than that. AcreateQuerywithenabled: falseonly observes the cache and turns the name bold once the data is there.src/routes/+page.svelteandsrc/routes/character/[id]/+page.svelteread the samecharactersQueries.detail(id)withcreateQuery, so a prefetched character renders without a loading state.src/routes/+layout.sveltecreates theQueryClientwithenabled: browser, so queries only run in the browser.
To run this example:
npm installnpm run dev