Need help for local storage delete
I started learning about local storage recently and I'm wondering why is it when I delete some of the lists it doesn't delete from local storage. It's weird like when I have 5 list and delete them, some of them deleted fine, however some are gone form the html but not in the local storage. That is weird.
Here is my code https://codepen.io/mingrkli/pen/RwyQwEe
19 Replies
it is because you use the index of what is shown on the page. but when you remove something from local storage, the index there shifts, while the indexes on your button events still refer to the original index.
what you can do is
when you create a list, give it an unique id (
new Date().getTime()
for example) and let the delete button point to that id
then you store the lists in an object with that id
so your local storage would look something like this
that way when you click the delete button. you can delete it from localstorage by that idinteresting. How would I target that ID to the local storage? I was thinking about creating an <p> that is hidden but I don't think that is great since if someone inspect the HTML if this was a different kind of project then they will see the ID.
just do the same. get it from local storage, and parse it. then you''ll have an object instead of an array. you can select the list by id
lists[id_of_list]
Oh... I just found a problem, how do I set the property by the parameter which is new Date().getTime() from your example?
you would append it to the existing lists
so listst is an object of objects
Ah... so like this?
yea, and you dont have to push.
oh ok, so it's like a 2 for 1. Thats cool
only the splice wont work now
to delete from an object you do
delete lists[datetimething]
I'm guessing this would also need to be changed
Ah ok, so for arrays we use forEach but for propertys we use for (list in lists). Ok i'm getting it now.
oh... thats interesting.
I think I did something wrong XD
for in
will give you the key
Can you explain what lists[list] means for me to understand it? I know that for each list in the lists object, when I print the list it will show the list but I also thought it would show what is in thoses list as well. However to do that you need to print lists[list] instead. What dose lists[list] mean in this context?
as you have seen, list will give you only the datetime (that is the key of the object entry)
to access the values of a specific object entry you do
objectname[objectkey]
in your case the object name is
lists
and the object key is the datetime
Ah ok, thankyou for all the information 🙂
no problem, good luck