diff --git a/src/components/DailyNoteWidget.tsx b/src/components/DailyNoteWidget.tsx index 3a1c79b56..4524405e4 100644 --- a/src/components/DailyNoteWidget.tsx +++ b/src/components/DailyNoteWidget.tsx @@ -2,128 +2,121 @@ import { useCallback, useEffect, useState } from "react"; -export default function DailyNoteWidget(){ - - const [loading,setLoading] = useState(false); - const [note,setNote] = useState(""); +export default function DailyNoteWidget() { + const [loading, setLoading] = useState(false); + const [note, setNote] = useState(""); const [yesterdayNote, setYesterdayNote] = useState(""); - const [showYesterday,setShowYesterday] = useState(false); - - useEffect(()=>{ - - const fetchNotes = async ()=>{ + const [showYesterday, setShowYesterday] = useState(false); - try{ + useEffect(() => { + const fetchNotes = async () => { + try { setLoading(true); const response = await fetch("/api/daily-note"); const data = await response.json(); - setNote(data.todayNote||""); - setYesterdayNote(data.yesterdayNote ||"" ); - - }catch(error){ + setNote(data.todayNote || ""); + setYesterdayNote(data.yesterdayNote || ""); + } catch (error) { console.error("Failed to fetch notes"); - }finally{ + } finally { setLoading(false); } - }; fetchNotes(); - },[]); - - -// auto save with debounce -// Wrapped in useCallback so the function reference is stable across renders. -// Without this, the auto-save useEffect would capture a stale closure of -// debounceFunction on any re-render that isn't caused by `note` changing, -// silently saving the wrong value or skipping the save entirely. -const debounceFunction = useCallback(async () => { - if (!note.trim()) return; - - try { - await fetch("/api/daily-note", { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ - note, - }), - }); - } catch (error) { - console.error("Failed to save note"); + }, []); + + // auto save with debounce + // Wrapped in useCallback so the function reference is stable across renders. + // Without this, the auto-save useEffect would capture a stale closure of + // debounceFunction on any re-render that isn't caused by `note` changing, + // silently saving the wrong value or skipping the save entirely. + const debounceFunction = useCallback(async () => { + if (!note.trim()) return; + + try { + await fetch("/api/daily-note", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + note, + }), + }); + } catch (error) { + console.error("Failed to save note"); + } + }, [note]); + + useEffect(() => { + const timeout = setTimeout(() => { + debounceFunction(); + }, 500); + return () => clearTimeout(timeout); + }, [note, debounceFunction]); + + if (loading) { + return ( +
Plan your coding session.
++ Plan your coding session. +