diff --git a/islands/CounterCard.tsx b/islands/CounterCard.tsx index c9748ef..8d5f8a6 100644 --- a/islands/CounterCard.tsx +++ b/islands/CounterCard.tsx @@ -10,7 +10,7 @@ interface SharedProps { export default function Counter(props: SharedProps) { const [count, setCount] = useState(0); - const [globalCount, setGlobalCount] = useState(props.globalCount); + const [globalCount, setGlobalCount] = useState(props.globalCount ?? 0); const [internalCount, setInternalCount] = useState(0); const onClick = () => { diff --git a/routes/index.tsx b/routes/index.tsx index a298eff..28fe867 100644 --- a/routes/index.tsx +++ b/routes/index.tsx @@ -15,9 +15,9 @@ export const handler: Handlers = { const bc = new BroadcastChannel("global-count"); const body = new ReadableStream({ start(controller) { - bc.addEventListener("message", () => { + bc.addEventListener("message", async () => { try { - const data = getGlobalStatistics(); + const data = await getGlobalStatistics(); const chunk = `data: ${JSON.stringify({globalCount: data})}\n\n`; controller.enqueue(new TextEncoder().encode(chunk)); } catch (e) { @@ -43,7 +43,7 @@ export const handler: Handlers = { }, POST: async (req, ctx) => { const body = await req.json(); - setGlobalStatistics(body.data); + await setGlobalStatistics(body.data); const bc = new BroadcastChannel("global-count"); bc.postMessage(new TextEncoder().encode(getGlobalStatistics().toString())) diff --git a/shared/db.ts b/shared/db.ts index 770578e..b81629b 100644 --- a/shared/db.ts +++ b/shared/db.ts @@ -1,17 +1,11 @@ const kv = await Deno.openKv(); -export function getGlobalStatistics(): number { - let res = 0; - kv.get(["global-statistics"]).then(v => { - res = v.value as number; - }); - - return res; +export async function getGlobalStatistics() { + const res = await kv.get(["global-statistics"]) ?? 0; + return res.value ?? 0; } -export function setGlobalStatistics(value: number) { - const pv = getGlobalStatistics(); - kv.set(["global-statistics"], pv + value).then(() => { - return; - }) +export async function setGlobalStatistics(value: number) { + const pv = await getGlobalStatistics(); + await kv.set(["global-statistics"], pv + value); }