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

BroadcastQueryClientProvider.tsx

70 lines1.9 KB

1'use client'
2import * as React from 'react'
3​
4import { broadcastQueryClientRestore } from '@tanstack/query-broadcast-client-experimental'
5import {
6 IsRestoringProvider,
7 QueryClientProvider,
8 useIsRestoring,
9} from '@tanstack/react-query'
10import type { BroadcastQueryClientRestoreOptions } from '@tanstack/query-broadcast-client-experimental'
11import type { OmitKeyof, QueryClientProviderProps } from '@tanstack/react-query'
12​
13export type BroadcastQueryClientProviderProps = QueryClientProviderProps & {
14 broadcastOptions: OmitKeyof<BroadcastQueryClientRestoreOptions, 'queryClient'>
16​
17/**
18 * Provides a QueryClient while gating descendant queries during cross-tab
19 * cache bootstrap. The session is cleaned up when the client changes or the
20 * provider unmounts.
21 */
22export const BroadcastQueryClientProvider = ({
23 children,
24 broadcastOptions,
25 ...props
26}: BroadcastQueryClientProviderProps): React.JSX.Element => {
27 const parentIsRestoring = useIsRestoring()
28 const [isRestoring, setIsRestoring] = React.useState(true)
29 const optionsRef = React.useRef(broadcastOptions)
30 const [previousClient, setPreviousClient] = React.useState(props.client)
31 const clientChanged = previousClient !== props.client
32​
33 React.useEffect(() => {
34 optionsRef.current = broadcastOptions
35 })
36​
37 React.useEffect(() => {
38 setPreviousClient(props.client)
39 }, [props.client])
40​
41 React.useEffect(() => {
42 setIsRestoring(true)
43 let mounted = true
44 const [cleanup, restorePromise] = broadcastQueryClientRestore({
45 ...optionsRef.current,
46 queryClient: props.client,
47 })
48​
49 restorePromise.then(() => {
50 if (mounted) {
51 setIsRestoring(false)
52 }
53 })
54​
55 return () => {
56 mounted = false
57 cleanup()
58 }
59 }, [props.client])
60​
61 return (
62 <QueryClientProvider {...props}>
63 <IsRestoringProvider
64 value={parentIsRestoring || isRestoring || clientChanged}
65 >
66 {children}
67 </IsRestoringProvider>
68 </QueryClientProvider>
69 )