Getting Started

Getting Started

Install and setup tRPC Vue-Query

Install

pnpm add @falcondev-oss/trpc-vue-query

Setup with Vue 3

main.ts
import { createTRPCVueQueryClient } from '@falcondev-oss/trpc-vue-query'
import { VueQueryPlugin, useQueryClient } from '@tanstack/vue-query'

import type { AppRouter } from '../your_server/trpc'

app.use(VueQueryPlugin)
app.use({
  install(app) {
    const queryClient = app.runWithContext(useQueryClient)
    const trpc = createTRPCVueQueryClient<AppRouter>({
      queryClient,
      trpc: {
        links: [
          httpBatchLink({
            url: '/api/trpc',
          }),
        ],
      },
    })

    app.provide('trpc', trpc)
  },
})
composables/useTRPC.ts
import { createTRPCVueQueryClient } from '@falcondev-oss/trpc-vue-query'

import type { AppRouter } from '../your_server/trpc'

export function useTRPC() {
  return inject('trpc') as ReturnType<typeof createTRPCVueQueryClient<AppRouter>>
}

Setup with Nuxt 3

Setup trpc-nuxt as described in their documentation. Then update the plugins/client.ts file:

plugins/client.ts
import { createTRPCVueQueryClient } from '@falcondev-oss/trpc-vue-query'
import { useQueryClient } from '@tanstack/vue-query'
import { httpBatchLink } from 'trpc-nuxt/client'

import type { AppRouter } from '~/server/trpc/routers'

export default defineNuxtPlugin(() => {
  const queryClient = useQueryClient()

  // ⬇️ use `createTRPCVueQueryClient` instead of `createTRPCNuxtClient` ⬇️
  const trpc = createTRPCVueQueryClient<AppRouter>({
    queryClient,
    trpc: {
      links: [
        httpBatchLink({
          url: '/api/trpc',
        }),
      ],
    },
  })

  return {
    provide: {
      trpc,
    },
  }
})
composables/useTRPC.ts
export function useTRPC() {
  return useNuxtApp().$trpc
}

Acknowledgements

Huge thanks to Robert Soriano for creating nuxt-trpc! We just adapted his work to work with Vue Query.


Copyright © 2024