Files
trpc-nuxt/README.md
2022-05-18 21:40:33 -07:00

1.9 KiB

tRPC-Nuxt

Version

End-to-end typesafe APIs with tRPC.io in Nuxt applications.

Install

npm i trpc-nuxt
// nuxt.config.ts
import { defineNuxtConfig } from 'nuxt'

export default defineNuxtConfig({
  modules: ['trpc-nuxt'],
  trpc: {
    baseURL: 'http://localhost:3000', // defaults to http://localhost:3000
    trpcURL: '/api/trpc', // defaults to /api/trpc
  },
  typescript: {
    strict: true // set this to true to make input/output types work
  }
})

Usage

Expose your tRPC routes under ~/server/trpc/index.ts:

// ~/server/trpc/index.ts
import type { inferAsyncReturnType } from '@trpc/server'
import * as trpc from '@trpc/server'

export const router = trpc
  .router<inferAsyncReturnType<typeof createContext>>()
  // queries and mutations...
  .query('hello', {
    resolve: () => 'world',
  })
  .query('bye', {
    resolve() {
      return {
        text: 'goodbye',
      }
    },
  })

Use the client like so:

<script setup lang="ts">
const client = useClient()

const greeting = await client.query('hello');
console.log(greeting); // => 👈 world

const farewell = await client.query('bye');
console.log(farewell); // => 👈 goodbye
</script>

useTRPCAsyncData

A composable that wraps Nuxt's useAsyncData with some modifications to have better error handlings.

const path = 'hello'
const client = useClient()

const {
  data,
  pending,
  error,
  refresh
} = await useTRPCAsyncData(path, () => client.query(path))

Recipes

Learn more about tRPC.io here.

License

MIT