-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata-provider.tsx
33 lines (23 loc) · 1.21 KB
/
data-provider.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
import { createContext, PropsWithChildren, ReactElement, useContext } from 'react'
import { isLocalOrDemo } from '@utils/env'
import { withFailInterceptor } from '../devtools/useAPIOverride'
import { DataService } from './data-service'
const DataProviderContext = createContext<DataService | null>(null)
/**
* Actual provider for specific implementation of DataService for the app. In demo and local development
* an interceptor is used to interact with DevTools for overriding whether a specific API fails or not.
*/
export function DataProvider({ dataService, children }: PropsWithChildren<{ dataService: DataService }>): ReactElement {
const wrappedDataService: DataService = isLocalOrDemo ? withFailInterceptor(dataService) : dataService
return <DataProviderContext.Provider value={wrappedDataService}>{children}</DataProviderContext.Provider>
}
export function useDataService(): DataService {
const adapter = useContext(DataProviderContext)
if (adapter === null) {
throw new Error('useNySykmeldingDataService must be used within a NySykmeldingFormDataProvider')
}
return adapter
}
export function useIsDataServiceInitialized(): boolean {
return useContext(DataProviderContext) !== null
}