Skip to content

Commit c7a0d77

Browse files
Add use service worker custom hook
1 parent 5cb5dcb commit c7a0d77

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

hooks/use-service-worker.ts

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'use client';
2+
3+
import { useEffect, useState } from 'react';
4+
import { Workbox } from 'workbox-window';
5+
6+
// Extend the Window interface to include workbox
7+
declare global {
8+
interface Window {
9+
workbox?: Workbox;
10+
}
11+
}
12+
13+
export function useServiceWorker() {
14+
const [isReady, setIsReady] = useState(false);
15+
const [needsRefresh, setNeedsRefresh] = useState(false);
16+
17+
useEffect(() => {
18+
if (
19+
typeof window !== 'undefined' &&
20+
'serviceWorker' in navigator &&
21+
window.workbox !== undefined
22+
) {
23+
const wb = new Workbox('/service-worker.js');
24+
25+
wb.addEventListener('installed', event => {
26+
if (event.isUpdate) {
27+
setNeedsRefresh(true);
28+
}
29+
});
30+
31+
wb.addEventListener('activated', () => {
32+
setIsReady(true);
33+
});
34+
35+
wb.register();
36+
37+
// window.workbox = wb; // can do this if in case of global access
38+
}
39+
}, []);
40+
41+
const refreshApp = () => {
42+
window.location.reload();
43+
};
44+
45+
return {
46+
isReady,
47+
needsRefresh,
48+
refreshApp,
49+
};
50+
}

0 commit comments

Comments
 (0)