Hello! I'm working on a todo-app and I'm trying to make the app save added todos after a page-refresh using localStorage, but it currently doesn't work properly. See codepen: https://codepen.io/TildaLindmanLundin/pen/QWJjPNO The code for localStor is from line 124. I think I need to move the 'getItem-codelines' (129 + 137) to line 9 and 10 - but I'm not sure how to make that work. Would be grateful for some guidance!😇
#localStorage-problem
1 messages · Page 1 of 1 (latest)
Ok, so the way I like to work with localStorage conceptually is this:
- I have a local variable(s) that contain the information I want
- when the page loads I initialize the local variable with whatever is in localStorage at that time
- I update localStorage whenever my variable changes
- I DO NOT directly interact with localStorage other than the aformentioned initial read then subsequent updates
It's really as simple as that...
Your code is a little, uh, different... I'm not sure why your render is touching localStorage at all - you should simply be rendering the contents of your todoListArr.
I also like to include some kind of an init() function... in your case it would simply read the contents of localStorage and stick the values in your array OR default the array to [] if there's nothing in localStorage.
Addtionally I like to have a couple of helper methods: readFromLocalStorage() and writeToLocalStorage() - this makes the process of reading/writing a little simpler to manage...
So, then some pseudocode would be this:
function init() {
readFromLocalStorage();
}
function createToDo() {
...
writeToLocalStorage();
}
function updateToDo() {
...
writeToLocalStorage();
}
function deleteToDo() {
...
writeToLocalStorage();
}
That should give you a nudge in the right direction!
Finally I would suggest you consider the "single responsibility principal" when coding... Each of your functions should only "DO" one thing (conceptually).
So a good example is your renderTodos() function - this renders todos AND manipulates localStorage... It should ONLY render the todos (as the name of the function implies), manipulating localStorage is the job of a different function and should be done elsewhere. This approach makes your code a little more modular and will help in the long run...