forked from vercel/swr
-
Notifications
You must be signed in to change notification settings - Fork 2
/
config-context.ts
66 lines (57 loc) · 1.58 KB
/
config-context.ts
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
import {
createContext,
createElement,
useContext,
useState,
FC,
PropsWithChildren
} from 'react'
import { cache as defaultCache } from './config'
import { initCache } from './cache'
import { mergeConfigs } from './merge-config'
import { UNDEFINED, mergeObjects } from './helper'
import { useIsomorphicLayoutEffect } from './env'
import {
SWRConfiguration,
FullConfiguration,
ProviderConfiguration,
Cache
} from '../types'
export const SWRConfigContext = createContext<Partial<FullConfiguration>>({})
const SWRConfig: FC<
PropsWithChildren<{
value?: SWRConfiguration &
Partial<ProviderConfiguration> & {
provider?: (cache: Readonly<Cache>) => Cache
}
}>
> = props => {
const { value } = props
// Extend parent context values and middleware.
const extendedConfig = mergeConfigs(useContext(SWRConfigContext), value)
// Should not use the inherited provider.
const provider = value && value.provider
// Use a lazy initialized state to create the cache on first access.
const [cacheContext] = useState(() =>
provider
? initCache(provider(extendedConfig.cache || defaultCache), value)
: UNDEFINED
)
// Override the cache if a new provider is given.
if (cacheContext) {
extendedConfig.cache = cacheContext[0]
extendedConfig.mutate = cacheContext[1]
}
// Unsubscribe events.
useIsomorphicLayoutEffect(
() => (cacheContext ? cacheContext[2] : UNDEFINED),
[]
)
return createElement(
SWRConfigContext.Provider,
mergeObjects(props, {
value: extendedConfig
})
)
}
export default SWRConfig