Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 24 additions & 14 deletions src/react/QueryClientProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,32 @@ import React from 'react'

import { QueryClient } from '../core'

const QueryClientContext = (() => {
const context = React.createContext<QueryClient | undefined>(undefined)
if (typeof window !== 'undefined') {
// @ts-ignore
window.ReactQueryClientContext = context
}
return context
})()
interface GlobalOrWindow {
ReactQueryClientContext?: React.Context<QueryClient | undefined>
}

const defaultContext = React.createContext<QueryClient | undefined>(undefined)

// We share the first and at least one
// instance of the context across the window
// to ensure that if React Query is used across
// different bundles or microfrontends they will
// all use the same **instance** of context, regardless
// of module scoping.
function getQueryClientContext() {
return typeof window !== 'undefined'
? // @ts-ignore
(window.ReactQueryClientContext as React.Context<
QueryClient | undefined
>) ?? QueryClientContext
: QueryClientContext
// @ts-ignore (for global)
if (typeof global !== 'undefined' || typeof window !== 'undefined') {
// @ts-ignore (for global)
const thisContext = (global || window) as GlobalOrWindow

if (!thisContext.ReactQueryClientContext) {
thisContext.ReactQueryClientContext = defaultContext
}

return thisContext.ReactQueryClientContext
}

return defaultContext
}

export const useQueryClient = () => {
Expand Down