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

useQueryClient.ts

44 lines1.4 KB

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