-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
broadcast-state.ts
43 lines (37 loc) · 1.15 KB
/
broadcast-state.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
import { Broadcaster } from '../types'
import { SWRGlobalState } from './global-state'
import * as revalidateEvents from '../constants'
import { createCacheHelper } from './cache'
export const broadcastState: Broadcaster = (
cache,
key,
state,
revalidate,
broadcast = true
) => {
const stateResult = SWRGlobalState.get(cache)
if (stateResult) {
const [EVENT_REVALIDATORS, STATE_UPDATERS, , FETCH] = stateResult
const revalidators = EVENT_REVALIDATORS[key]
const updaters = STATE_UPDATERS[key]
const [get] = createCacheHelper(cache, key)
// Cache was populated, update states of all hooks.
if (broadcast && updaters) {
for (let i = 0; i < updaters.length; ++i) {
updaters[i](state)
}
}
// If we also need to revalidate, only do it for the first hook.
if (revalidate) {
// Invalidate the key by deleting the concurrent request markers so new
// requests will not be deduped.
delete FETCH[key]
if (revalidators && revalidators[0]) {
return revalidators[0](revalidateEvents.MUTATE_EVENT).then(
() => get().data
)
}
}
return get().data
}
}