Files
trpc-nuxt/docs/content/1.get-started/3.client.md
2022-12-18 23:31:55 -08:00

2.0 KiB

title, description
title description
Client tRPC-Nuxt provides first class integration with tRPC.

Nuxt client

The magic of tRPC is making strongly typed API calls without relying on code generation. With full-stack TypeScript projects, you can directly import types from the server into the client! This is a vital part of how tRPC works.

Initialize a tRPC client

Create a typesafe client via a Nuxt plugin with the createTRPCNuxtClient method from trpc-nuxt/client, and add a links array with a terminating link. If you want to learn more about tRPC links, check out the docs here:

::alert{type="info"} createTRPCNuxtClient extends createTRPCProxyClient and adds a useQuery method built on top of useAsyncData. ::

import { createTRPCNuxtClient, httpBatchLink } from 'trpc-nuxt/client'
import type { AppRouter } from '~/server/trpc/routers'

export default defineNuxtPlugin(() => {
  const client = createTRPCNuxtClient<AppRouter>({
    links: [
      httpBatchLink({
        url: '/api/trpc',
      }),
    ],
  })

  return {
    provide: {
      client,
    },
  }
})

As you can see, we passed AppRouter as a type argument of createTRPCNuxtClient. This returns a strongly typed client instance, a proxy that mirrors the structure of your AppRouter on the client:

<script setup lang="ts">
const { $client } = useNuxtApp()

const getUser = await $client.getUser.useQuery('id_bilbo');
// => { data: { id: 'id_bilbo', name: 'Bilbo' }, pending: false, error: false };

const bilbo = await $client.getUser.query('id_bilbo');
// => { id: 'id_bilbo', name: 'Bilbo' };
const frodo = await $client.createUser.mutate({ name: 'Frodo' });
// => { id: 'id_frodo', name: 'Frodo' };
</script>