Git Product home page Git Product logo

trpc-vue-query's Introduction

tRPC Vue Query

NPM version

A tRPC wrapper around @tanstack/vue-query. This package provides a set of hooks to use tRPC with Vue Query.

Installation

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

Documentation

👉 https://trpc-vue-query.falcondev.io/getting-started 👈

Usage with Vue

1. Create client & composable

import { createTRPCVueQueryClient } from '@falcondev-oss/trpc-vue-query'
import type { AppRouter } from '../your_server/trpc'
import { VueQueryPlugin, useQueryClient } from '@tanstack/vue-query'

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)
  },
})
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>>
}

2. Use it in your components

<script lang="ts" setup>
const { data: greeting } = useTRPC().hello.useQuery({ name: 'World' })
</script>

<template>
  <div>
    <h1>{{ greeting }}</h1>
  </div>
</template>

3. Passing vue-query options

<script lang="ts" setup>
const { data: greeting } = useTRPC().hello.useQuery(
  { name: 'World' },
  {
    refetchOnMount: false,
    refetchOnReconnect: false,
    refetchOnWindowFocus: false,
    staleTime: 1000 * 60 * 5,
  },
)
</script>

<template>
  <div>
    <h1>{{ greeting }}</h1>
  </div>
</template>

4. Using the useMutation hook

<script lang="ts" setup>
const name = ref('')
const { mutate: updateGreeting } = useTRPC().hello.update.useMutation({
  onSuccess: () => {
    console.log('Greeting updated')
  },
})
</script>

<template>
  <div>
    <input v-model="name" type="text" />
    <button @click="() => updateGreeting({ name })">Update greeting</button>
  </div>
</template>

Usage with trpc-nuxt

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

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,
    },
  }
})
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.

trpc-vue-query's People

Contributors

drjume avatar github-actions[bot] avatar louishaftmann avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

chechehuang

trpc-vue-query's Issues

How to handle SWR cache in useQuery() to avoid fetching if the SWR cache exists?

How to handle SWR cache in useQuery() to avoid fetching if the SWR cache exists?

[trpc].ts

export default createNuxtApiHandler({
	router: appRouter,
	createContext,
	responseMeta(opts) {
		const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
		return {
			headers: {
				"cache-control":  `s-maxage=300, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
			},
		};
	},
});

projects.vue page

const { data, isPending, suspense } = useTrpc().project.getProjects.useQuery(() => {
    return {
      category: route_category,
      pageSize: pageSize.value,
      page: currentPage.value,
    }
  },
    {
      refetchOnMount: false,
      refetchOnReconnect: false,
      refetchOnWindowFocus: false,
      staleTime: 1000 * 60 * 5,
    },
  )

  onServerPrefetch(async () => {
    await suspense()
  })

At the moment, each time the project page loads, it refetches

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.