Skip to main content

Set up the Svelte Query Integration

1. Install dependencies

The following dependencies should be installed

npm install @trpc/client @trpc/server @tanstack/svelte-query @bevm0/trpc-svelte-query 

2. Create your AppRouter

src/lib/server/trpc.ts
import { z } from "zod";
import { initTRPC } from '@trpc/server';

const t = initTRPC.create();

const appRouter = t.router({
getUser: t.procedure
.input(z.object({ id: z.string() }))
.query(() => ({ name: 'Pardo' })),

createUser: t.procedure
.input(z.object({ name: z.string() }))
.mutation(() => 'Felis'),
});

export type AppRouter = typeof appRouter;

3. Import your AppRouter and Create tRPC hooks

Create a set of strongly-type Svelte hooks from your AppRouter type signature with createTRPCSvelte.

tip

These are meant to be used in components only. See how to use context directly in SvelteKit load functions here.

src/lib/trpc.ts
import { createTRPCSvelte } from '@bevm0/trpc-svelte-query';
import { httpBatchLink } from '@trpc/client';
import type { AppRouter } from '$lib/server/trpc';

export const trpc = createTRPCSvelte<AppRouter>({
links: [
httpBatchLink({ url: 'http://localhost:5173/api/trpc' })
]
});

4. Add Svelte-Query providers

Set up and connect Svelte Query, which is documented in more depth here.

tip

If you already use Svelte Query in your application, you should re-use the QueryClient and QueryClientProvider you already have.

src/routes/+layout.svelte
<script lang="ts">
import { QueryClient, QueryClientProvider } from '@tanstack/svelte-query';
import { trpc } from '$lib/trpc'

const queryClient = new QueryClient()

// the tRPC context needs
// 1. an untyped tRPC client to make the request
// 2. a query client to control
// 3. (optional) options to control the behavior of context
trpc.setContext(trpc.client, queryClient)
</script>

<QueryClientProvider client={queryClient}>
<slot />
</QueryClientProvider>
note

setContext is intended to be analogous to trpc.Provider.

The main difference is that the provided tRPC client should be untyped. This TRPCUntypedClient and a typesafe TRPCProxyClient can be accessed via trpc.client and trpc.proxy respectively.

5. Fetch data

You can now use the tRPC Svelte Query integration to call queries and mutations on your API.

note

useQuery, useMutation, etc. from @trpc/react-query and @tanstack/react-query are renamed to createQuery, createMutation, etc. based on the naming conventions in @trpc/svelte-query

src/routes/+page.svelte
<script lang="ts">
import { trpc } from '$lib/trpc'

const userQuery = trpc.getUser.createQuery({ id: 'Eden' });
const userCreator = trpc.createUser.createMutation();

function handleClick() {
$userCreator.mutate({ name: 'Elysia' })
}
</script>

<div>
<p>{$userQuery.data?.name}</p>
<button on:click={handleClick}>Create Elysia</button>
</div>