-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheffect.js
48 lines (44 loc) · 1.18 KB
/
effect.js
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
import { useEffect, useRef, useCallback } from 'react'
import { useStateValue } from './general'
export const useDidUpdate = cb => {
const first = useRef(true)
useEffect(() => {
if (first.current) {
first.current = false
} else {
return cb()
}
}, [cb])
}
// wait to fetch non-urgent resources until urgent requests are complete and
// app is no longer suspensed
export const useDelayedPrefetch = fetchCb => {
const componentLoading = useStateValue('ui componentLoading')
const ref = useRef({ status: 'START', value: null })
const fetch = useCallback(() => {
fetchCb()
ref.current.status = null
}, [fetchCb])
useEffect(() => {
switch (ref.current.status) {
case 'START':
ref.current.status = 'TIMEOUT'
window.setTimeout(() => {
if (ref.current.value) {
ref.current.status = 'CHECK'
} else {
fetch()
}
}, 100)
// fallthrough
case 'TIMEOUT':
ref.current.value = componentLoading
break
case 'CHECK':
if (!componentLoading) {
fetch()
ref.current.status = null
}
}
}, [componentLoading, fetch])
}