mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 20:19:33 +01:00
1ef0caa18e5c3d57f4edb761db9f43f89c53729a
tRPC-Nuxt
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:
const client = useClient() // auto-imported
const greeting = await client.query('hello')
console.log(greeting) // => 👈 world
const farewell = await client.query('bye')
console.log(farewell) // => 👈 goodbye
useAsyncQuery
A thin wrapper around useAsyncData.
The first argument is a [path, input]-tuple - if the input is optional, you can omit the, input-part.
You'll notice that you get autocompletion on the path and automatic typesafety on the input.
const {
data,
pending,
error,
refresh
} = await useAsyncQuery(['getUser', { id: 69 }], {
// pass useAsyncData options here
server: true
})
Recipes
Learn more about tRPC.io here.
License
MIT
Languages
TypeScript
88.1%
Vue
11.9%