UNPKG

2.96 kBPlain TextView Raw
1import type {
2 ThunkDispatch,
3 ActionCreatorWithoutPayload, // Workaround for API-Extractor
4} from '@reduxjs/toolkit'
5import { createAction } from './rtkImports'
6
7export const onFocus = /* @__PURE__ */ createAction('__rtkq/focused')
8export const onFocusLost = /* @__PURE__ */ createAction('__rtkq/unfocused')
9export const onOnline = /* @__PURE__ */ createAction('__rtkq/online')
10export const onOffline = /* @__PURE__ */ createAction('__rtkq/offline')
11
12let initialized = false
13
14/**
15 * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.
16 * It requires the dispatch method from your store.
17 * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,
18 * but you have the option of providing a callback for more granular control.
19 *
20 * @example
21 * ```ts
22 * setupListeners(store.dispatch)
23 * ```
24 *
25 * @param dispatch - The dispatch method from your store
26 * @param customHandler - An optional callback for more granular control over listener behavior
27 * @returns Return value of the handler.
28 * The default handler returns an `unsubscribe` method that can be called to remove the listeners.
29 */
30export function setupListeners(
31 dispatch: ThunkDispatch<any, any, any>,
32 customHandler?: (
33 dispatch: ThunkDispatch<any, any, any>,
34 actions: {
35 onFocus: typeof onFocus
36 onFocusLost: typeof onFocusLost
37 onOnline: typeof onOnline
38 onOffline: typeof onOffline
39 },
40 ) => () => void,
41) {
42 function defaultHandler() {
43 const handleFocus = () => dispatch(onFocus())
44 const handleFocusLost = () => dispatch(onFocusLost())
45 const handleOnline = () => dispatch(onOnline())
46 const handleOffline = () => dispatch(onOffline())
47 const handleVisibilityChange = () => {
48 if (window.document.visibilityState === 'visible') {
49 handleFocus()
50 } else {
51 handleFocusLost()
52 }
53 }
54
55 if (!initialized) {
56 if (typeof window !== 'undefined' && window.addEventListener) {
57 // Handle focus events
58 window.addEventListener(
59 'visibilitychange',
60 handleVisibilityChange,
61 false,
62 )
63 window.addEventListener('focus', handleFocus, false)
64
65 // Handle connection events
66 window.addEventListener('online', handleOnline, false)
67 window.addEventListener('offline', handleOffline, false)
68 initialized = true
69 }
70 }
71 const unsubscribe = () => {
72 window.removeEventListener('focus', handleFocus)
73 window.removeEventListener('visibilitychange', handleVisibilityChange)
74 window.removeEventListener('online', handleOnline)
75 window.removeEventListener('offline', handleOffline)
76 initialized = false
77 }
78 return unsubscribe
79 }
80
81 return customHandler
82 ? customHandler(dispatch, { onFocus, onFocusLost, onOffline, onOnline })
83 : defaultHandler()
84}