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