forked from reduxjs/redux-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindowEventHandling.ts
67 lines (58 loc) · 1.88 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
62
63
64
65
66
67
import { QueryStatus } from '../apiState'
import type { QueryCacheKey } from '../apiState'
import { onFocus, onOnline } from '../setupListeners'
import type { SubMiddlewareApi, SubMiddlewareBuilder } from './types'
export const build: SubMiddlewareBuilder = ({
reducerPath,
context,
api,
refetchQuery,
}) => {
const { removeQueryResult } = api.internalActions
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 || !querySubState) return
if (Object.keys(subscriptionSubState).length === 0) {
api.dispatch(
removeQueryResult({
queryCacheKey: queryCacheKey as QueryCacheKey,
})
)
} else if (querySubState.status !== QueryStatus.uninitialized) {
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))
}
}
}
})
}
}