forked from reduxjs/redux-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindowEventHandling.ts
61 lines (53 loc) · 1.63 KB
/
windowEventHandling.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
import { QueryStatus } from '../apiState'
import { onFocus, onOnline } from '../setupListeners'
import type { SubMiddlewareApi, SubMiddlewareBuilder } from './types'
export const build: SubMiddlewareBuilder = ({
reducerPath,
context,
refetchQuery,
}) => {
return (mwApi) =>
(next) =>
(action): any => {
const result = next(action)
if (onFocus.match(action)) {
refetchValidQueries(mwApi, 'refetchOnFocus')
}
if (onOnline.match(action)) {
refetchValidQueries(mwApi, 'refetchOnReconnect')
}
return result
}
function refetchValidQueries(
api: SubMiddlewareApi,
type: 'refetchOnFocus' | 'refetchOnReconnect'
) {
const state = api.getState()[reducerPath]
const queries = state.queries
const subscriptions = state.subscriptions
context.batch(() => {
for (const queryCacheKey of Object.keys(subscriptions)) {
const querySubState = queries[queryCacheKey]
const subscriptionSubState = subscriptions[queryCacheKey]
if (
!subscriptionSubState ||
Object.keys(subscriptionSubState).length === 0 ||
!querySubState ||
querySubState.status === QueryStatus.uninitialized
)
return
const shouldRefetch =
Object.values(subscriptionSubState).some(
(sub) => sub[type] === true
) ||
(Object.values(subscriptionSubState).every(
(sub) => sub[type] === undefined
) &&
state.config[type])
if (shouldRefetch) {
api.dispatch(refetchQuery(querySubState, queryCacheKey))
}
}
})
}
}