Skip to content

Commit 19e0723

Browse files
fix: cross-module react query context (TanStack#1805)
* fix: cross-module react query context * ditch the node types for simplicity and ignore `global` for now
1 parent ff619d0 commit 19e0723

File tree

1 file changed

+24
-14
lines changed

1 file changed

+24
-14
lines changed

src/react/QueryClientProvider.tsx

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,32 @@ import React from 'react'
22

33
import { QueryClient } from '../core'
44

5-
const QueryClientContext = (() => {
6-
const context = React.createContext<QueryClient | undefined>(undefined)
7-
if (typeof window !== 'undefined') {
8-
// @ts-ignore
9-
window.ReactQueryClientContext = context
10-
}
11-
return context
12-
})()
5+
interface GlobalOrWindow {
6+
ReactQueryClientContext?: React.Context<QueryClient | undefined>
7+
}
138

9+
const defaultContext = React.createContext<QueryClient | undefined>(undefined)
10+
11+
// We share the first and at least one
12+
// instance of the context across the window
13+
// to ensure that if React Query is used across
14+
// different bundles or microfrontends they will
15+
// all use the same **instance** of context, regardless
16+
// of module scoping.
1417
function getQueryClientContext() {
15-
return typeof window !== 'undefined'
16-
? // @ts-ignore
17-
(window.ReactQueryClientContext as React.Context<
18-
QueryClient | undefined
19-
>) ?? QueryClientContext
20-
: QueryClientContext
18+
// @ts-ignore (for global)
19+
if (typeof global !== 'undefined' || typeof window !== 'undefined') {
20+
// @ts-ignore (for global)
21+
const thisContext = (global || window) as GlobalOrWindow
22+
23+
if (!thisContext.ReactQueryClientContext) {
24+
thisContext.ReactQueryClientContext = defaultContext
25+
}
26+
27+
return thisContext.ReactQueryClientContext
28+
}
29+
30+
return defaultContext
2131
}
2232

2333
export const useQueryClient = () => {

0 commit comments

Comments
 (0)