Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage.setItem() not working: not writing

I am trying to create a book tracker app that uses localStorage. However, when I set an item - what happens is that no error message is given but it doesn't log to localStorage. Here is my code:

      
      //var currentId = parseInt(localStorage.getItem("currid"))+1;
      
      var nameOfItem = "bookPackage"+id;
      localStorage.setItem(nameOfItem, readBooks);

Assume that currid is already preset in localStorage as a number.

When I go to the console and type in localStorage, here is the result:

Storage {length: 0}

Why is it not working???

Edit: readBooks is an object.

like image 370
anonsaicoder9 Avatar asked Jan 30 '26 08:01

anonsaicoder9


2 Answers

You can only store strings into local storage, if you want to store an object you need to JSON.stringify(obj) first.

var str = "22";
localStorage.setItem('key', str);
var getStr = localStorage.getItem('key');
console.log(parseInt(getStr));

let obj = {a: 'a1', b: 'a2'};
localStorage.setItem('key2', JSON.stringify(obj));
let getObject = localStorage.getItem('key2');
console.log(JSON.parse(getObject));
like image 162
sonEtLumiere Avatar answered Jan 31 '26 22:01

sonEtLumiere


As @sonEtLumiere has already mentioned, you can only store strings into local/session storage, so if you have objects/arrays, you will have to stringify them with JSON prior to storing them into local/session storage. I'm not sure what "readBooks" is, but since it's plural, I'm assuming it's an array. Because of this, you'll need to use JSON.stringify(data) to store that information.

When you need to retrieve object/array data from local/session storage, you'll have to parse out the data using JSON.

JSON.parse(data)

Just remember, Stringify IN to storage, Parse OUT of storage.

like image 38
kvncnls Avatar answered Jan 31 '26 21:01

kvncnls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!