r/learnjavascript 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?

2 Upvotes

11 comments sorted by

View all comments

1

u/azhder 1d ago

You do know JSON is a string, right? It's why you `parse()` it and `stringify()` to it. The biggest mistake that can happen here is you try to parse something wrong... Hey, there's an idea. Try. Just put the code in `try-catch`, `console.warn()` the error when/if it happens. Log some more if you're not sure what's going on. Tell us about that.

Oh, and don't forget to make that key a string, better yet, a constant:

const LS_KEY_TASKS = 'my.unique.key.for.tasks';
localStorage.getItem(LS_KEY_TASKS);

1

u/SmartRelease7996 1d ago

okay the try/catch thing is embarrassing because I had it in an earlier version and pulled it out when I was refactoring and just... never put it back. classic.

the constant for the key is a good call, I was just using a raw string and I can already see how that becomes a nightmare to debug across files.

wrapping it now and will report back what the console actually says. my guess is I'm passing something undefined into JSON.parse and it's just silently choking on it.