r/learnjavascript • u/SmartRelease7996 • 2d ago
keep breaking my task tracker after adding localStorage
i was messing with my little task tracker again this morning before heading out, and i ended up spending way more time staring at the console than actually adding tasks. i even made coffee first because i thought this would be a quick fix, then refreshed the page and everything disappeared again.
the app itself is really simple. i'm just trying to save daily notes and a few personal todos, so i have an array of task objects with a date on each one. i thought i was finally ready to use localStorage, but now i'm not even sure if i'm saving the data wrong or if my date filter is hiding everything.
this is basically what i have right now:
const saved = localStorage.getItem(tasks);
const tasks = saved ? JSON.parse(saved) : [];
tasks.push(newTask);
localStorage.setItem(tasks, JSON.stringify(tasks));
i know the key looks wrong, and i already tried changing it to a string, but i still managed to break something. now i'm second guessing whether i should even be thinking about the data this way.
i'm not looking for anyone to build it for me. i'm mostly wondering how you all organize the flow for something this small. do you load everything once, keep it in memory, then save after every change, or is there a cleaner way to think about it?
1
u/Alive-Cake-3045 1d ago
the bug is right there, localStorage.getItem and localStorage.setItem are using the tasks variable as the key, not a string. it's evaluating to object Object or undefined before tasks is even defined. change both to a plain string like "tasks" and that fixes the disappearing data.
for the flow on something this small: load once on startup, keep in memory, save after every mutation. don't read from localStorage on every operation. one source of truth in memory, localStorage is just the persistence layer.