How do I update localStorage items?

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?



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


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:

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

You can use full featured Angular module angular-local-storage

An AngularJS module that gives you access to the browsers local storage with cookie fallback


myApp.controller('MainCtrl', function($scope, localStorageService) {
  function submit(key, val) {
   return localStorageService.set(key, val);


myApp.controller('MainCtrl', function($scope, localStorageService) {
  function getItem(key) {
   return localStorageService.get(key);

setItem wont work instead it will create another item in localStorage with the same name

Instead directly use

localStorage.item = (what ever the change that you want in the item)


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 = "newName";
const modifiedndstrigifiedForStorage = JSON.stringify(parsedObject);
localStorage.setItem("ship", strigifiedForStorage);


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.