Bug fixed — checkbox persistence in my React Todo app Problem: after checking a todo and reloading the page, the checkbox would appear unchecked. Root cause: the checked prop in the checkbox expects a boolean, but localStorage sometimes contained "true" / "false" (strings) or inconsistent shapes. That made the UI show wrong values after reload. Fix (two parts): Normalize stored data on init — use a lazy useState initializer to read from localStorage once and convert "true"/"false" strings to booleans safely. Update state immutably — toggle using map() and spread so the isCompleted flag is correctly flipped and persisted. Key snippets: // Initialize todos from localStorage (lazy initializer) const [todos, setTodos] = useState(() => { try { const raw = localStorage.getItem('todos'); if (!raw) return []; const parsed = JSON.parse(raw); return parsed.map(t => ({ id: t.id ?? uuidv4(), todo: typeof t.todo === 'string' ? t.todo : '', // normalize isCompleted: boolean or "true"/"false" isCompleted: typeof t.isCompleted === 'boolean' ? t.isCompleted : t.isCompleted === 'true', })); } catch { return []; } }); // Toggle handler (immutable update) const handleCheckbox = id => { setTodos(prev => prev.map(item => item.id === id ? { ...item, isCompleted: !item.isCompleted } : item )); }; // Persist whenever todos change useEffect(() => { localStorage.setItem('todos', JSON.stringify(todos)); }, [todos]); Result: after checking a todo it stays checked after reload ✅ Learning: !!value coerces to boolean for quick UI checks (checked={!!item.isCompleted}), but the real fix is normalizing your stored data on load so you don’t rely on ad-hoc coercion. Thoughts welcome! #react #javascript #webdev #frontend #100DaysOfCode

To view or add a comment, sign in

Explore content categories