Getting Started
Usage
The basics of using tRPC Vue Query
Querying data
Basic usage
<script lang="ts" setup>
const { data: shoppingCart } = useTRPC().cart.get.useQuery()
</script>
With parameters
You can pass input parameters directly to the useQuery
function. These parameters can also be reactive.
<script lang="ts" setup>
const productId = ref(1)
const { data: product } = useTRPC().product.getById.useQuery(productId)
</script>
With options
You can pass options as the second argument to the useQuery
function.
<script lang="ts" setup>
const { data: notifications } = useTRPC().notifications.get.useQuery(undefined, {
refetchInterval: 30000,
})
</script>
Mutating data
<script lang="ts" setup>
const { mutate: addToCart } = useTRPC().cart.addProduct.useMutation({
onSuccess: () => {
console.log('Product added to cart')
},
})
function handleFormSubmit(productId: string) {
addToCart(productId)
}
</script>
Helpers
invalidate()
You can invalidate a query by calling the invalidate
function.
<script lang="ts" setup>
const trpc = useTRPC()
const { mutate: addToCart } = trpc.cart.addProduct.useMutation({
onSuccess: () => {
// this will invalidate and refetch the `cart.get` query
trpc.cart.get.invalidate()
},
})
</script>
setQueryData()
You can update the query data manually by calling the setQueryData
function.
<script lang="ts" setup>
const trpc = useTRPC()
const { mutate: addToCart } = trpc.cart.addProduct.useMutation({
onSuccess: (newCart) => {
trpc.cart.get.setQueryData(newCart)
},
})
</script>
key()
You can get the query key by calling the key
function. With the key you can access all the other Tanstack Query features.
<script lang="ts" setup>
const trpc = useTRPC()
const cartKey = trpc.cart.get.key()
const productKey = trpc.product.getById.key(1)
</script>