Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

custom-client.md

89 lines2.4 KB

1---
2id: custom-client
3title: Custom Client
4---
5​
6### Custom client
7​
8Vue Query allows providing custom `QueryClient` for Vue context.
9​
10It might be handy when you need to create `QueryClient` beforehand to integrate it with other libraries that do not have access to the Vue context.
11​
12For this reason, `VueQueryPlugin` accepts either `QueryClientConfig` or `QueryClient` as a plugin options.
13​
14If You provide `QueryClientConfig`, `QueryClient` instance will be created internally and provided to Vue context.
15​
16```tsx
17const vueQueryPluginOptions: VueQueryPluginOptions = {
18 queryClientConfig: {
19 defaultOptions: { queries: { staleTime: 60 * 60 * 1000 } },
20 },
22app.use(VueQueryPlugin, vueQueryPluginOptions)
23```
24​
25```tsx
26const myClient = new QueryClient(queryClientConfig)
27const vueQueryPluginOptions: VueQueryPluginOptions = {
28 queryClient: myClient,
30app.use(VueQueryPlugin, vueQueryPluginOptions)
31```
32​
33### Custom context key
34​
35You can also customize the key under which `QueryClient` will be accessible in Vue context. This can be useful is you want to avoid name clashing between multiple apps on the same page with Vue2.
36​
37It works both with default, and custom `QueryClient`
38​
39```tsx
40const vueQueryPluginOptions: VueQueryPluginOptions = {
41 queryClientKey: 'Foo',
43app.use(VueQueryPlugin, vueQueryPluginOptions)
44```
45​
46```tsx
47const myClient = new QueryClient(queryClientConfig)
48const vueQueryPluginOptions: VueQueryPluginOptions = {
49 queryClient: myClient,
50 queryClientKey: 'Foo',
52app.use(VueQueryPlugin, vueQueryPluginOptions)
53```
54​
55To use the client registered under a custom key, get it with `useQueryClient` and pass it as the second argument
56​
57```js
58useQuery(
59 {
60 queryKey: ['query1'],
61 queryFn: fetcher,
62 },
63 useQueryClient('Foo'),
65```
66​
67The devtools look up the client under the default key, so pass the client to them through the `client` prop as well
68​
69```vue
70<script setup>
71import { useQueryClient } from '@tanstack/vue-query'
72import { VueQueryDevtools } from '@tanstack/vue-query-devtools'
73​
74const queryClient = useQueryClient('Foo')
75</script>
76​
77<template>
78 <VueQueryDevtools :client="queryClient" />
79</template>
80```
81​
82Internally custom key will be combined with default query key as a suffix. But user do not have to worry about it.
83​
84```tsx
85const vueQueryPluginOptions: VueQueryPluginOptions = {
86 queryClientKey: 'Foo',
88app.use(VueQueryPlugin, vueQueryPluginOptions) // -> VUE_QUERY_CLIENT:Foo
89```