-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryProvider.tsx
More file actions
72 lines (63 loc) · 1.85 KB
/
QueryProvider.tsx
File metadata and controls
72 lines (63 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { useEffect, type ReactNode } from 'react'
import { Context, type ContextValue } from 'query/react:context'
import { createQuery } from 'query:index'
/**
* Props for the QueryProvider component, extending the context value
* configuration with optional children.
*/
export interface QueryProviderProps extends ContextValue {
/**
* The child elements to render within the provider context.
*/
children?: ReactNode
}
/**
* A React component that provides query context to its descendants.
* Creates a query instance if not provided, sets up a BroadcastChannel
* for cross-tab synchronization, and makes the query available to all
* child components via React context.
*
* @param props - The provider configuration and children.
*
* @example
* ```tsx
* import { QueryProvider, createQuery } from '@studiolambda/query/react'
*
* const query = createQuery({ fetcher: customFetcher })
*
* function App() {
* return (
* <QueryProvider query={query} clearOnForget>
* <MyComponents />
* </QueryProvider>
* )
* }
* ```
*/
export function QueryProvider({
children,
clearOnForget,
ignoreTransitionContext,
query,
}: QueryProviderProps) {
const localQuery = query ?? createQuery()
useEffect(
function () {
// Guard against environments where BroadcastChannel is unavailable
// (e.g. certain edge runtimes or older server-side environments).
if (typeof BroadcastChannel === 'undefined') {
return
}
const broadcast = new BroadcastChannel('query')
localQuery.configure({ broadcast })
const unsubscribe = localQuery.subscribeBroadcast()
return function () {
unsubscribe()
broadcast.close()
}
},
[localQuery]
)
const value = { query: localQuery, clearOnForget, ignoreTransitionContext }
return <Context value={value}>{children}</Context>
}