Open History to see the last commit
1import type { QueryClient } from '@tanstack/query-core'
2import type { Context, JSX } from 'solid-js'
3import {
4 createContext,
5 useContext,
6 onMount,
7 onCleanup,
8 mergeProps,
9} from 'solid-js'
10import type { ContextOptions } from './types'
11β
12declare global {
13 interface Window {
14 SolidQueryClientContext?: Context<QueryClient | undefined>
15 }
16}
17β
18export const defaultContext = createContext<QueryClient | undefined>(undefined)
19const QueryClientSharingContext = createContext<boolean>(false)
20β
21// If we are given a context, we will use it.
22// Otherwise, if contextSharing is on, we share the first and at least one
23// instance of the context across the window
24// to ensure that if Solid Query is used across
25// different bundles or microfrontends they will
26// all use the same **instance** of context, regardless
27// of module scoping.
28function getQueryClientContext(
29 context: Context<QueryClient | undefined> | undefined,
30 contextSharing: boolean,
31) {
32 if (context) {
33 return context
34 }
35 if (contextSharing && typeof window !== 'undefined') {
36 if (!window.SolidQueryClientContext) {
37 window.SolidQueryClientContext = defaultContext
38 }
39β
40 return window.SolidQueryClientContext
41 }
42β
43 return defaultContext
44}
45β
46export const useQueryClient = ({ context }: ContextOptions = {}) => {
47 const queryClient = useContext(
48 getQueryClientContext(context, useContext(QueryClientSharingContext)),
49 )
50β
51 if (!queryClient) {
52 throw new Error('No QueryClient set, use QueryClientProvider to set one')
53 }
54β
55 return queryClient
56}
57β
58type QueryClientProviderPropsBase = {
59 client: QueryClient
60 children?: JSX.Element
61}
62type QueryClientProviderPropsWithContext = ContextOptions & {
63 contextSharing?: never
64} & QueryClientProviderPropsBase
65type QueryClientProviderPropsWithContextSharing = {
66 context?: never
67 contextSharing?: boolean
68} & QueryClientProviderPropsBase
69β
70export type QueryClientProviderProps =
71 | QueryClientProviderPropsWithContext
72 | QueryClientProviderPropsWithContextSharing
73β
74export const QueryClientProvider = (
75 props: QueryClientProviderProps,
76): JSX.Element => {
77 const mergedProps = mergeProps(
78 {
79 contextSharing: false,
80 },
81 props,
82 )
83 onMount(() => mergedProps.client.mount())
84 onCleanup(() => mergedProps.client.unmount())
85β
86 const QueryClientContext = getQueryClientContext(
87 mergedProps.context,
88 mergedProps.contextSharing,
89 )
90β
91 return (
92 <QueryClientSharingContext.Provider
93 value={!mergedProps.context && mergedProps.contextSharing}
94 >
95 <QueryClientContext.Provider value={mergedProps.client}>
96 {mergedProps.children}
97 </QueryClientContext.Provider>
98 </QueryClientSharingContext.Provider>
99 )
100}