I have some local storage items that are a list of objects.
console.log(localStorageService.get("kittens"));
would output something like:
[
{"name": "fluffy", "color": "white" },
{"name": "luna", "color": "black" }
]
let's say I want to update luna's color to brown.
var myKitten = localStorageService.get('kittens').filter(function(kitten){
return kitten.name == "luna";
})[0];
myKitten.color = "brown";
And then I can't figure out how to update just the single record of the local storage.
In reality I'm sending a request to the server to update the record, however it doesn't get updated in my app.
When the response comes back I want to update the record in local storage as well, but I seem to be able to only update the ENTIRE local storage item ("kittens"). I don't see a way to do this in the docs, but feel that there should be a way to do this that I'm overlooking.
Localstorage values are saved as strings.
So you have to save it like this:
var kittens = [
{"name": "fluffy", "color": "white" },
{"name": "luna", "color": "black" }
]
// Save array in local storage as string
localStorage.setItem("kittens",JSON.stringify(kittens));
// Get back item "kittens" from local storage
var kittensFromLocalStorage = JSON.parse(localStorage.getItem("kittens"));
// Change value
kittensFromLocalStorage[1].name = "jasmine";
// Save the new item with updated value
localStorage.setItem("kittens",JSON.stringify(kittensFromLocalStorage));
Or you can use some support library as LocalForage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With