Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

setFocusHandler.js

63 lines1.7 KB

1import { isOnline, isDocumentVisible, Console, isServer } from './utils'
2import { defaultConfigRef } from './config'
3import { queryCaches } from './queryCache'
4​
5const visibilityChangeEvent = 'visibilitychange'
6const focusEvent = 'focus'
7​
8const onWindowFocus = () => {
9 const { refetchAllOnWindowFocus } = defaultConfigRef.current
10​
11 if (isDocumentVisible() && isOnline()) {
12 queryCaches.forEach(queryCache =>
13 queryCache
14 .refetchQueries(query => {
15 if (!query.instances.length) {
16 return false
17 }
18​
19 if (query.config.manual === true) {
20 return false
21 }
22​
23 if (query.shouldContinueRetryOnFocus) {
24 // delete promise, so `fetch` will create new one
25 delete query.promise
26 return true
27 }
28​
29 if (typeof query.config.refetchOnWindowFocus === 'undefined') {
30 return refetchAllOnWindowFocus
31 } else {
32 return query.config.refetchOnWindowFocus
33 }
34 })
35 .catch(Console.error)
36 )
37 }
39​
40let removePreviousHandler
41​
42export function setFocusHandler(callback) {
43 // Unsub the old watcher
44 if (removePreviousHandler) {
45 removePreviousHandler()
46 }
47 // Sub the new watcher
48 removePreviousHandler = callback(onWindowFocus)
50​
51setFocusHandler(handleFocus => {
52 // Listen to visibillitychange and focus
53 if (!isServer && window?.addEventListener) {
54 window.addEventListener(visibilityChangeEvent, handleFocus, false)
55 window.addEventListener(focusEvent, handleFocus, false)
56​
57 return () => {
58 // Be sure to unsubscribe if a new handler is set
59 window.removeEventListener(visibilityChangeEvent, handleFocus)
60 window.removeEventListener(focusEvent, handleFocus)
61 }
62 }
63})