2021-04-26 10:10:47 +00:00
|
|
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
|
|
import { register } from "register-service-worker";
|
|
|
|
|
|
|
|
export const useServiceWorker = (timeout: number) => {
|
|
|
|
const [updateAvailable, setUpdateAvailable] = useState<boolean>(false);
|
|
|
|
const registrationRef = useRef<ServiceWorkerRegistration>();
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const interval = (setInterval(() => {
|
|
|
|
if (registrationRef.current) {
|
|
|
|
registrationRef.current.update();
|
|
|
|
}
|
|
|
|
}, timeout) as unknown) as number;
|
|
|
|
return () => clearInterval(interval);
|
|
|
|
}, [timeout]);
|
|
|
|
|
|
|
|
const onRegistered = (registration: ServiceWorkerRegistration) => {
|
|
|
|
registrationRef.current = registration;
|
|
|
|
};
|
|
|
|
|
2021-09-14 09:06:28 +00:00
|
|
|
const onUpdate = (registration: ServiceWorkerRegistration) => {
|
|
|
|
setUpdateAvailable(!!registration?.waiting);
|
|
|
|
};
|
2021-04-26 10:10:47 +00:00
|
|
|
|
|
|
|
const update = useCallback(() => {
|
2021-09-14 09:06:28 +00:00
|
|
|
if (updateAvailable && registrationRef.current?.waiting) {
|
2021-04-26 10:10:47 +00:00
|
|
|
registrationRef.current.waiting.postMessage("update");
|
|
|
|
}
|
|
|
|
}, [updateAvailable]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
register("/sw.js", {
|
|
|
|
registered: onRegistered,
|
2022-06-21 09:36:55 +00:00
|
|
|
updated: onUpdate,
|
2021-04-26 10:10:47 +00:00
|
|
|
});
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
return { update, updateAvailable };
|
|
|
|
};
|