pstream is dead; long live pstream taciturnaxolotl.github.io/pstream-ng/
at main 41 lines 1.1 kB view raw
1import { useEffect, useRef } from "react"; 2 3import { useBannerStore } from "@/stores/banner"; 4 5export function useOnlineListener() { 6 const updateOnline = useBannerStore((s) => s.updateOnline); 7 const ref = useRef<boolean>(true); 8 9 useEffect(() => { 10 let counter = 0; 11 12 let abort: null | AbortController = null; 13 const interval = setInterval(() => { 14 // if online try once every 10 iterations intead of every iteration 15 counter += 1; 16 if (ref.current) { 17 if (counter < 10) return; 18 } 19 counter = 0; 20 21 if (abort) abort.abort(); 22 abort = new AbortController(); 23 const signal = abort.signal; 24 fetch("/ping.txt", { signal }) 25 .then(() => { 26 updateOnline(true); 27 ref.current = true; 28 }) 29 .catch((err) => { 30 if (err.name === "AbortError") return; 31 updateOnline(false); 32 ref.current = false; 33 }); 34 }, 5000); 35 36 return () => { 37 clearInterval(interval); 38 if (abort) abort.abort(); 39 }; 40 }, [updateOnline]); 41}