mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
feat: add connection monitor hook for reactive failure detection
This commit is contained in:
@@ -0,0 +1,48 @@
|
|||||||
|
import { useEffect } from "react";
|
||||||
|
import { useConnectionStore } from "@/stores/connection-store";
|
||||||
|
|
||||||
|
export function useConnectionMonitor() {
|
||||||
|
useEffect(() => {
|
||||||
|
const store = useConnectionStore;
|
||||||
|
|
||||||
|
const handleOffline = () => store.getState().setOffline();
|
||||||
|
const handleOnline = () => {
|
||||||
|
store.getState().setOnline();
|
||||||
|
store.getState().startPolling();
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener("offline", handleOffline);
|
||||||
|
window.addEventListener("online", handleOnline);
|
||||||
|
|
||||||
|
store.getState().checkHealth();
|
||||||
|
|
||||||
|
const unsubscribe = store.subscribe((state, prev) => {
|
||||||
|
if (state.status === prev.status) return;
|
||||||
|
|
||||||
|
if (state.status === "disconnected") {
|
||||||
|
store.getState().startPolling();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.status === "reconnected") {
|
||||||
|
store.getState().stopPolling();
|
||||||
|
store.getState().refreshStaleData();
|
||||||
|
setTimeout(() => {
|
||||||
|
if (store.getState().status === "reconnected") {
|
||||||
|
store.setState({ status: "connected" });
|
||||||
|
}
|
||||||
|
}, 2500);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.status === "offline") {
|
||||||
|
store.getState().stopPolling();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("offline", handleOffline);
|
||||||
|
window.removeEventListener("online", handleOnline);
|
||||||
|
store.getState().stopPolling();
|
||||||
|
unsubscribe();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user