"use client"; import { useEffect } from "react"; import { getPendingWrites, clearPendingWrite } from "@/lib/db"; export function useSyncQueue() { useEffect(() => { let cancelled = false; async function drain() { if (cancelled) return; const pending = await getPendingWrites(); for (const w of pending) { if (cancelled) return; try { const method = w.op === "delete" ? "DELETE" : w.op === "create" ? "POST" : "PUT"; const res = await fetch(w.endpoint, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(w.body), }); if (res.ok) await clearPendingWrite(w.id); } catch { return; // try again on next online event } } } const handle = () => { void drain(); }; window.addEventListener("online", handle); void drain(); return () => { cancelled = true; window.removeEventListener("online", handle); }; }, []); }