January 13, 2023 ~ 1 min read

How to setup Svelte Query with SvelteKit

Making sure server side state is synced with client side state with SvelteQuery is really easy in SvelteKit.

Add the following to your Layout files.

+layout.ts typescript
import type {LayoutLoad} from './$types'
import {QueryClient} from '@tanstack/svelte-query'

export const load: LayoutLoad = async () => {
    return {queryClient: new QueryClient()}
}
+layout.svelte typescript
<script lang="ts">
    import type {PageData} from './$types'
    import {QueryClientProvider} from '@tanstack/svelte-query'

    export let data: PageData
</script>

<QueryClientProvider client={data.queryClient}>
    <slot />
</QueryClientProvider>

And then you can start doing the following in your pages.

+page.ts typescript
import type {PageLoad} from './$types'

export const load: PageLoad = async ({fetch, parent}) => {
    const {queryClient} = await parent()
    queryClient.prefetchQuery(['your-key'], () => fetch('your-endpoint'))
}
+page.svelte typescript
<script lang="ts">
    import {createQuery} from '@tanstack/svelte-query' // This data would be cached by the prefetch in +page.ts so no fetch would actually
    happen here const yourQuery = createQuery(['your-key'], () => fetch('your-endpoint'))
</script>

{$yourQuery.data}

This way data is hydrated on the client and on first page load there would be only one request fired.