diff --git a/islands/Routine.tsx b/islands/Routine.tsx index 56b03ae..0717d70 100644 --- a/islands/Routine.tsx +++ b/islands/Routine.tsx @@ -29,6 +29,34 @@ export function Routine( const tasks = useSignal(props.tasks) const currentPhase = useSignal(toPhase()) + const reload = async () => { + console.log('reloading...') + const newData = await (await fetch(location.href, { + headers: { accept: 'application/json' }, + })).json() + tasks.value = newData + console.log('new tasks:', newData) + } + + useEffect(() => { + let es = new EventSource('/api/tasks') + console.log('Streaming task events...') + + es.addEventListener('message', (e) => { + console.log('task event from server:', e) + reload() + }) + + es.addEventListener('error', async (e) => { + // try and reconnect + console.log('Streaming todo events error:', e) + es.close() + const backoff = 10000 + Math.random() * 5000 + await new Promise((resolve) => setTimeout(resolve, backoff)) + es = new EventSource('/api/tasks') + }) + }, []) + useEffect(() => { if (IS_BROWSER) { setInterval(() => { diff --git a/routes/api/tasks.ts b/routes/api/tasks.ts index b7e73c0..6a79b1f 100644 --- a/routes/api/tasks.ts +++ b/routes/api/tasks.ts @@ -114,7 +114,11 @@ export const handler: Handlers = { ) } else { return new Response( - JSON.stringify(Array.fromAsync(kv.list({ prefix: ['task'] }))), + JSON.stringify( + (await Array.fromAsync(kv.list({ prefix: ['task'] }))).map((r) => + r.value + ), + ), ) } }, diff --git a/routes/routine.tsx b/routes/routine.tsx index 4437056..d26c037 100644 --- a/routes/routine.tsx +++ b/routes/routine.tsx @@ -9,11 +9,14 @@ interface Data { } export const handler: Handlers = { - async GET(_req, ctx) { + async GET(req, ctx) { const tasks = (await Array.fromAsync(kv.list({ prefix: ['task'] }))).map( - (r) => r.value + (r) => r.value, ) - console.log({ tasks }) + const accept = req.headers.get('accept') + if (accept === 'application/json') { + return new Response(JSON.stringify(tasks)) + } return ctx.render({ tasks }) }, }