How do I update localStorage items?

32,792

Solution 1

To do that with native JavaScript, you would do something like this:

localStorage.setItem('itemKey', JSON.stringify(yourObject));
var item = JSON.parse(localStorage.getItem('itemKey'));

Within the context of angular, you should make a localStorage service as a wrapper around localStorage and inject it into your service or controller. Or you could inject $window and use it directly off of that like: $window.localStorage

Solution 2

A response specifically for the asker of this duplicate question:

LocalStorage can only store strings, which is why you're stringifying your object before storing it. To manipulate the stored string as an object, you can pass it to JSON.parse (assuming it's properly JSON-formatted). Then to store the modified version, you need to convert it back into a string.

// Creates JSON-formatted object, converts it to a string and stores the string as "ship"
const ship = { name: "black pearl", captain: "Jack Sparrow" };
const originalStringifiedForStorgage = JSON.stringify(ship);
localStorage.setItem("ship", JSON.stringify(ship));

// Retrieves the string and converts it to a JavaScript object 
const retrievedString = localStorage.getItem("ship");
const parsedObject = JSON.parse(retrievedString);

// Modifies the object, converts it to a string and replaces the existing `ship` in LocalStorage
parsedObject.name = "newName";
const modifiedndstrigifiedForStorage = JSON.stringify(parsedObject);
localStorage.setItem("ship", strigifiedForStorage);

Solution 3

If the object is in JSON format (not sure if Angular uses a different format) you could probably use the setItem() and getItem() methods to update and retrieve local storage items!

For example taken from the following post: http://thejackalofjavascript.com/storing-objects-html5-local-storage/

var me = {name:'myname',age:99,gender:'myGender'};
localStorage.setItem("user",me);
//fetch object
console.log(localStorage.getItem("user")); // will return "[object Object]"
Share:
32,792
MaxwellLynn
Author by

MaxwellLynn

Front end web developer working in Bristol as well as freelance on the side.

Updated on July 19, 2022

Comments

  • MaxwellLynn
    MaxwellLynn almost 2 years

    I'm having a problem where the cached object doesn't resemble the correct data so I figured it I can push up the most uptodate version to the browser cache it will solve my problem.

    How do you update your localStorage with a new object? So if I had a controller with that had an assessment updated. How can I push that assessment object up to the localStorage?