简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM