Files
trpc-nuxt/README.md
Robert Soriano f4a9d7e127 update readme
2022-05-17 17:22:24 -07:00

2.3 KiB

tRPC-Nuxt

Version

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

Install

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

export default defineNuxtConfig({
  modules: ['trpc-nuxt'],
})

Usage

Create your tRPC routes and context under ~/trpc/index.ts:

// ~/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',
  })

// optional
export const createContext = () => {
  // ...
  return {
    /** context data */
  }
}

// optional
export const responseMeta = () => {
  // ...
  return {
    // { headers: ... }
  }
}

Use the client like so:

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

const data = await client.query('hello')

console.log(data) // => 👈 world
</script>

Composables

Composables are auto-imported.

useClient()

A typesafe client with the createTRPCClient method from @trpc/client.

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

const bilbo = await client.query('getUser', 'id_bilbo');
// => { id: 'id_bilbo', name: 'Bilbo' };

const frodo = await client.mutation('createUser', { name: 'Frodo' });
// => { id: 'id_frodo', name: 'Frodo' };
</script>

useClientQuery

client.query wrapped in useAsyncData.

<script setup lang="ts">
const { data, pending, refresh, error } = await useClientQuery('getUser', 'id_bilbo');

console.log(data.value) // => { id: 'id_frodo', name: 'Frodo' };
</script>

useLazyClientQuery

client.query wrapped in useLazyAsyncData.

<script setup lang="ts">
const { data, pending, refresh, error } = await useLazyClientQuery('getUser', 'id_bilbo');

console.log(data.value) // => { id: 'id_frodo', name: 'Frodo' };
</script>