anonsaicoder9
anonsaicoder9

Reputation: 115

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.

Upvotes: 2

Views: 10357

Answers (2)

kvncnls
kvncnls

Reputation: 261

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.

Upvotes: 1

sonEtLumiere
sonEtLumiere

Reputation: 4572

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));

Upvotes: 4

Related Questions