Reputation: 1
I'm in the middle of creating a simple tv shows tracker (which ones I have seen/watching at this moment) and as I don't backend myself, I decided to store all the data in local storage. Right now I'm able to store all the shows in the local storage with no problem. The problem occurs when I need to update data in local storage (to give you a specific example - please look at the screen below):
screenshot of my list with local storage shown
As you can see I have those buttons to adjust the number of show's seasons and episodes (they work just fine). But I have no idea how to store that updated value and that value only in local storage. Down below you can find the code that reads data from local storage and use them to create list:
function readFromMemory(){
const data = JSON.parse(localStorage.getItem('seriale'));
data.forEach(element => {
serialeMemory.push(element);
let serialInMemory = new SerialeList(element.pos, element.img, element.name, element.score, element.userEpisodes, element.episodes,element.userSeasons, element.seasons, element.status, element.id);
serialInMemory.inject(); //Creates list from class
serialInMemory.episodeUpDown(); //Gives functionality to episodes buttons
serialInMemory.seasonUpDown(); //Give functionality to seasons buttons
});
deleteSerialRow(); //method to delete the whole row from list and from local storage
}
I know how to filter out to show only what I want by using Array.prototype.filter
method. But I don't know how to push only that row into localstorage
.
I would very gladly appreciate any insight.
Thank you.
Upvotes: 0
Views: 629
Reputation: 1
To be honest I kinda solved it myself. Here's the method that works:
updateSeasons(id, changeValue){
const data = JSON.parse(localStorage.getItem('seriale'));
const filter = data.filter(element => element.id === id);
filter[0].userSeasons = changeValue;
for(let i = 0; i< serialeMemory.length; i++){
if(serialeMemory[i].id === filter[0].id) serialeMemory[i].userSeasons = changeValue;
}
localStorage.setItem('seriale', JSON.stringify(serialeMemory));
}
I've used the very same array I have kept pushing during the DOMLoad event and it works just fine. But yeah, I probably should have attach a key to every single show, but I think I'm fine with my solution. Thank you anyway!
Upvotes: 0
Reputation: 800
Well, since you only use one key („seriale”), there's no other way as to deserialise it, modify the object accordingly (e.g. using Array.prototype.splice
), serialise it again and call localStorage.setItem
with the same key and the updated and serialised object.
Upvotes: 1