Set up the Svelte Query Integration
1. Install dependencies
The following dependencies should be installed
- npm
- yarn
- pnpm
npm install @trpc/client @trpc/server @tanstack/svelte-query @bevm0/trpc-svelte-query
yarn add @trpc/client @trpc/server @tanstack/svelte-query @bevm0/trpc-svelte-query
pnpm add @trpc/client @trpc/server @tanstack/svelte-query @bevm0/trpc-svelte-query
2. Create your AppRouter
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
.
These are meant to be used in components only.
See how to use context
directly in SvelteKit load functions here.
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.
If you already use Svelte Query in your application, you should re-use the QueryClient
and QueryClientProvider
you already have.
<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>
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.
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
<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>