Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular update local storage single object

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.

like image 786
awwester Avatar asked Jul 26 '26 09:07

awwester


1 Answers

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

like image 52
ronIDX Avatar answered Jul 28 '26 06:07

ronIDX