-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUpdateProvider.tsx
78 lines (70 loc) · 2.04 KB
/
UpdateProvider.tsx
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
68
69
70
71
72
73
74
75
76
77
78
import {
createContext,
type PropsWithChildren,
useMemo,
useState,
useCallback,
useEffect,
} from 'react';
import {useRegisterSW} from 'virtual:pwa-register/react';
type UpdateHandler = {
needRefresh: boolean;
setIsHandlerOverridden: (override: boolean) => void;
update: () => void;
};
export const UpdateContext = createContext<UpdateHandler>({
// Hybrid interface combining the vite-pwa react example: https://vite-pwa-org.netlify.app/frameworks/react.html
// along with a way 1 child component to override the auto update.
needRefresh: false,
setIsHandlerOverridden: () => undefined,
update: () => undefined,
});
export function UpdateProvider({children}: PropsWithChildren) {
const {
needRefresh: [needRefresh],
updateServiceWorker,
} = useRegisterSW({
onRegistered(registration) {
console.log('SW Registered:', registration);
if (registration) {
setInterval(
() => {
void registration.update();
},
60 * 60 * 1000,
);
}
},
onRegisterError(error) {
console.error('SW registration error', error);
},
});
const update = useCallback(() => {
console.log('Updating');
void updateServiceWorker(true);
}, [updateServiceWorker]);
// If one day multiple child components want to delay the update,
// this should use a stack with push/pop when overrides happen.
const [isHandlerOverridden, setIsHandlerOverridden] =
useState<boolean>(false);
useEffect(() => {
if (needRefresh && !isHandlerOverridden) {
update();
}
}, [needRefresh, isHandlerOverridden, update]);
const updateContext = useMemo<UpdateHandler>(
() => ({
// Consider forcing this to false if the override is true
// Maybe that would be more consistent? Or maybe just more complex???
needRefresh,
setIsHandlerOverridden,
update,
}),
[setIsHandlerOverridden, needRefresh, update],
);
return (
<UpdateContext.Provider value={updateContext}>
{children}
</UpdateContext.Provider>
);
}