1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
"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);
};
}, []);
}
|