forked from Sage-Bionetworks/Synapse-React-Client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SynapseContext.tsx
60 lines (53 loc) · 1.45 KB
/
SynapseContext.tsx
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
import React, { useContext } from 'react'
import { QueryClient, QueryClientProvider } from 'react-query'
const defaultQueryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30 * 1000, // 30s
retry: false, // SynapseClient knows which queries to retry
},
},
})
export type SynapseContextType = {
accessToken?: string
isInExperimentalMode: boolean
utcTime: boolean
}
/**
* This must be exported to use the context in class components.
*/
export const SynapseContext = React.createContext<
SynapseContextType | undefined
>(undefined)
export type SynapseContextProviderProps = {
synapseContext?: SynapseContextType
queryClient?: QueryClient
}
/**
* Provides context necessary for most components in SRC
* @param param0
* @returns
*/
export const SynapseContextProvider: React.FunctionComponent<SynapseContextProviderProps> = ({
children,
synapseContext,
queryClient,
}) => {
return (
<SynapseContext.Provider value={synapseContext}>
<QueryClientProvider client={queryClient ?? defaultQueryClient}>
{children}
</QueryClientProvider>
</SynapseContext.Provider>
)
}
export const SynapseContextConsumer = SynapseContext.Consumer
export function useSynapseContext(): SynapseContextType {
const context = useContext(SynapseContext)
if (context === undefined) {
throw new Error(
'useSynapseContext must be used within a SynapseContextProvider',
)
}
return context
}