Open History to see the last commit
1import { hasInjectionContext, inject } from 'vue-demi'
2β
3import { getClientKey } from './utils'
4import type { QueryClient } from './queryClient'
5β
6/**
7 * Retrieves the `QueryClient` installed by `VueQueryPlugin`, via Vue's
8 * `inject`. Must be called inside `setup()` or another function that supports
9 * an injection context.
10 *
11 * @example
12 * ;```vue
13 * <script setup lang="ts">
14 * import { useQueryClient } from '@tanstack/vue-query'
15 *
16 * const queryClient = useQueryClient()
17 *
18 * function invalidate() {
19 * queryClient.invalidateQueries({ queryKey: ['todos'] })
20 * }
21 * </script>
22 * ```
23 *
24 * @param id - The `queryClientKey` passed to `VueQueryPlugin` β only needed
25 * when multiple `QueryClient`s are installed in the same app.
26 * @returns The installed `QueryClient`.
27 * @throws {Error} If called outside an injection context, or if no
28 * `QueryClient` was installed via `VueQueryPlugin`.
29 */
30export function useQueryClient(id = ''): QueryClient {
31 // ensures that `inject()` can be used
32 if (!hasInjectionContext()) {
33 throw new Error(
34 'vue-query hooks can only be used inside setup() function or functions that support injection context.',
35 )
36 }
37β
38 const key = getClientKey(id)
39 const queryClient = inject<QueryClient>(key)
40β
41 if (!queryClient) {
42 throw new Error(
43 "No 'queryClient' found in Vue context, use 'VueQueryPlugin' to properly initialize the library.",
44 )
45 }
46β
47 return queryClient
48}