|
| 1 | +import { InstallTabs } from '@site/src/components/InstallTabs'; |
| 2 | + |
| 3 | +# Vue Query |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +<InstallTabs packageName="@ts-rest/vue-query @tanstack/vue-query" /> |
| 8 | + |
| 9 | +This is a client using `@ts-rest/vue-query`, using `@tanstack/vue-query` under the hood. |
| 10 | + |
| 11 | +## Init TanStack Query Vue plugin |
| 12 | + |
| 13 | +To use the query client in your Vue app, you'll need to initialise the `vue-query` client in your app. |
| 14 | + |
| 15 | +```ts |
| 16 | +import { VueQueryPlugin } from '@tanstack/vue-query'; |
| 17 | + |
| 18 | +createApp(App).use(VueQueryPlugin).mount('#app'); |
| 19 | +``` |
| 20 | + |
| 21 | +## initQueryClient |
| 22 | + |
| 23 | +The below snippet is how you'd create a query client, this is pretty much the same structure as the `@ts-rest/core` client. |
| 24 | + |
| 25 | +```tsx |
| 26 | +import { initQueryClient } from '@ts-rest/vue-query'; |
| 27 | + |
| 28 | +export const client = initQueryClient(router, { |
| 29 | + baseUrl: 'http://localhost:3333', |
| 30 | + baseHeaders: {}, |
| 31 | + api?: () => ... // <- Optional Custom API Fetcher (see below) |
| 32 | +}); |
| 33 | +``` |
| 34 | + |
| 35 | +To customise the API, follow the same docs as the core client [here](/docs/core/custom) |
| 36 | + |
| 37 | +:::tip |
| 38 | + |
| 39 | +By default, ts-rest encodes query parameters as regular URL encoded strings (with support for nested objects, arrays etc) with full decode compatibility from [`qs`](https://www.npmjs.com/package/qs) |
| 40 | + |
| 41 | +To encode query parameters as JSON, you can use the `jsonQuery` option, please note you'll need to configure your backend to support decoding JSON query parameters. |
| 42 | + |
| 43 | +```tsx |
| 44 | +export const client = initQueryClient(router, { |
| 45 | + ..., |
| 46 | + jsonQuery: true |
| 47 | +}); |
| 48 | + |
| 49 | +``` |
| 50 | + |
| 51 | +::: |
| 52 | + |
| 53 | +## useQuery and useMutation |
| 54 | + |
| 55 | +Once you've created a client using `initQueryClient`, you may traverse the object (in the exact same structure as your contract layout) to find the query or mutation you want to use. |
| 56 | + |
| 57 | +```tsx |
| 58 | +const queryResult = client.posts.get.useQuery( |
| 59 | + ['posts'], // <- queryKey |
| 60 | + () => { |
| 61 | + params: { |
| 62 | + id: '1'; |
| 63 | + } |
| 64 | + }, // <- Query params, Params, Body etc (all typed) |
| 65 | + { staleTime: 1000 } // <- vue-query options (optional) |
| 66 | +); |
| 67 | +``` |
| 68 | + |
| 69 | +### using dynamic parameters |
| 70 | + |
| 71 | +To use dynamic parameters, you can add a reactive vue `Ref` to the `queryKey` to trigger automatic refetching, when the reference changes. |
| 72 | + |
| 73 | +The following example will refetch the query everytime the `postId` changes and is truthy. |
| 74 | + |
| 75 | +```tsx |
| 76 | +const postId = computed(() => selectedPost.value.id); |
| 77 | + |
| 78 | +const queryResult = client.posts.get.useQuery( |
| 79 | + ['posts', postId], // <- queryKey with reactive ref |
| 80 | + (context) => { |
| 81 | + params: { |
| 82 | + id: postId.value; // or use queryKey passed to context: context.queryKey[1] |
| 83 | + } |
| 84 | + }, |
| 85 | + { enabled: computed(() => !!postId.value) } // <- make sure to use computed values for reactive options |
| 86 | +); |
| 87 | +``` |
| 88 | + |
| 89 | +:::tip |
| 90 | + |
| 91 | +The design philosophy of `@ts-rest/vue-query` is to make it as easy as possible to use `vue-query` with `@ts-rest`. This means that the `useQuery` and `useMutation` hooks are as close to the original `vue-query` hooks as possible, as such we don't abstract away from the query keys or the options. Only the query function itself! |
| 92 | + |
| 93 | +::: |
| 94 | + |
| 95 | +```html |
| 96 | +<template> |
| 97 | + <div class="App"> |
| 98 | + <h1>Posts from posts-service</h1> |
| 99 | + |
| 100 | + <div v-if="isLoading">Loading...</div> |
| 101 | + <div v-if="error">Error: {{ error }}</div> |
| 102 | + |
| 103 | + <div v-if="data"> |
| 104 | + <div v-for="post in data.body" :key="post.id"> |
| 105 | + <h2>{{ post.title }}</h2> |
| 106 | + <p>{{ post.content }}</p> |
| 107 | + </div> |
| 108 | + </div> |
| 109 | + </div> |
| 110 | +</template> |
| 111 | + |
| 112 | +<script lang="ts" setup> |
| 113 | + // Effectively a useQuery hook |
| 114 | + const { data, error, isLoading } = client.getPosts.useQuery(['posts']); |
| 115 | +
|
| 116 | + // Effectively a useMutation hook |
| 117 | + const { mutate, isLoading } = client.posts.create.useMutation(); |
| 118 | +</script> |
| 119 | +``` |
| 120 | + |
| 121 | +:::info |
| 122 | + |
| 123 | +When destructing the response from `useQuery` or `useMutation`, remember that ts-rest returns a `status` and `body` property, so you'll need to destructure those as well. |
| 124 | + |
| 125 | +The reason for this is error handling! Please see the [Relevant Docs](/docs/core/errors#client-error-typing) |
| 126 | + |
| 127 | +::: |
| 128 | + |
| 129 | +## Regular Query and Mutations |
| 130 | + |
| 131 | +`@ts-rest/vue-query` allows for a regular fetch or mutation if you want, without having to initialise two different clients, one with `@ts-rest/core` and one with `@ts-rest/vue-query`. |
| 132 | + |
| 133 | +```typescript |
| 134 | +// Normal fetch |
| 135 | +const { body, status } = await client.posts.get.query(); |
| 136 | + |
| 137 | +// useQuery hook |
| 138 | +const { data, isLoading } = client.posts.get.useQuery(); |
| 139 | +``` |
| 140 | + |
| 141 | +## useInfiniteQuery |
| 142 | + |
| 143 | +One fantastic feature of `vue-query` is the ability to create infinite queries. This is a great way to handle pagination. |
| 144 | + |
| 145 | +[Prisma's Docs](https://www.prisma.io/docs/concepts/components/prisma-client/pagination) explain the concepts of cursor and offset pagination fantastically, especially if you use Prisma client with `@ts-rest` |
| 146 | + |
| 147 | +### Cursor Pagination |
| 148 | + |
| 149 | +This is a simple cursor based pagination example, |
| 150 | + |
| 151 | +```typescript |
| 152 | +const { isLoading, data, hasNextPage, fetchNextPage } = useInfiniteQuery( |
| 153 | + queryKey, |
| 154 | + ({ pageParam = 1 }) => pageParam, |
| 155 | + { |
| 156 | + getNextPageParam: (lastPage, allPages) => lastPage.nextCursor, |
| 157 | + getPreviousPageParam: (firstPage, allPages) => firstPage.prevCursor, |
| 158 | + } |
| 159 | +); |
| 160 | +``` |
| 161 | + |
| 162 | +### Offset Pagination |
| 163 | + |
| 164 | +This example specifically uses an API with `skip` and `take` query parameters, so this is requires slightly more configuration than a regular query (hence the complicated looking getNextPageParam) |
| 165 | + |
| 166 | +```tsx |
| 167 | +const PAGE_SIZE = 5; |
| 168 | + |
| 169 | +export function Index() { |
| 170 | + const { isLoading, data, hasNextPage, fetchNextPage } = |
| 171 | + client.getPosts.useInfiniteQuery( |
| 172 | + ['posts'], |
| 173 | + ({ pageParam = { skip: 0, take: PAGE_SIZE } }) => ({ |
| 174 | + query: { skip: pageParam.skip, take: pageParam.take }, |
| 175 | + }), |
| 176 | + { |
| 177 | + getNextPageParam: (lastPage, allPages) => |
| 178 | + lastPage.status === 200 |
| 179 | + ? lastPage.body.count > allPages.length * PAGE_SIZE |
| 180 | + ? { take: PAGE_SIZE, skip: allPages.length * PAGE_SIZE } |
| 181 | + : undefined |
| 182 | + : undefined, |
| 183 | + } |
| 184 | + ); |
| 185 | + |
| 186 | + if (isLoading) { |
| 187 | + return <div>Loading...</div>; |
| 188 | + } |
| 189 | + |
| 190 | + if (!data) { |
| 191 | + return <div>No posts found</div>; |
| 192 | + } |
| 193 | + |
| 194 | + const posts = data.pages.flatMap((page) => |
| 195 | + page.status === 200 ? page.body.posts : [] |
| 196 | + ); |
| 197 | + |
| 198 | + //... |
| 199 | +} |
| 200 | +``` |
0 commit comments