localStorage.setItem() not working: not writing - javascript

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.

Related

Access nested object values from local storage

How to get nested object values from localstorage.
For example:
"metadata":"{
"receiver":{"name":"John"},
"document":{"type":"Sample doc"},
"issuer":{"signatory":"Admin2"}}",
"options": "{"title\":"Document Title","expireOn":"2022-03-12T00:00:00.000Z"}"
I need to store and get values of name:john, type:sample, signatory:Admin.
localStorage.setItem('metadata', JSON.stringify(data.metadata));
let metadata = localStorage.getItem('metadata');
console.log('metadata: ', JSON.parse(metadata));
Thank you.
At first you should get the localStorage values and convert that to a JavaScript Object.
let metadata = JSON.parse(localStorage.getItem('metadata'))
Then you can easily get or store data.
// Store
metadata.receiver.name = 'example'
// Get
let name = metadata.receiver.name
You can do this way for other values also.
Have tried to save and get your JSON in localstorage.
Steps for getting nested object value.
Step 1: Sample JSON
var data = {"metadata":{"receiver":{"name":"John"},"document":{"type":"Sampledoc"},"issuer":{"signatory":"Admin2"}},"options":{"title":"DocumentTitle","expireOn":"2022-03-12T00:00: 00.000Z"}};
Step 2: Converting JSON Object to a String format and Save in
Localstorage window.localStorage.setItem("metadata", JSON.stringify(data.metadata));
Step 3: Fetch Stringify JSON from localstorage and parse var metadata = JSON.parse(window.localStorage.getItem("metadata"));
Step 4: Fetch nested Object value console.log(metadata.receiver.name)
Hope this answer is useful.

How to save multiple form values as a consolidated String in Local Storage and retrieve them to be displayed on the browser

I'm trying to create a 'Notes' application which is basically a form that the user uses to enter 2 values, a name and a note.
I am displaying the 2 values as a 'consolidated note' on the browser with a delete button.
There can be any number of notes entered using this form.
How can I save the consolidated notes(i.e with Creator's name and the actual content of the note) in a string or array in the Local Storage and then retrieve it to be displayed on the browser when the browser reloads?
I understand that we save it using JSON.stringify and retrieve the data from the Local Storage using JSON.parse, but I'm unsure of how to save these multiple notes in the LOCAL Storage and retrieve them. Please help!
function addNoteLocalStorage(){
let notes = getNotesFromStorage();
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
obj.creator = creator;
obj.note = note;
let jsonstring = JSON.stringify(obj);
//create an array and push the string to the Object Array
objArray.push(jsonstring);
//store the new note
localStorage.setItem('notes', objArray);
}
The above code saves more than one note in the Local Storage.
Currently, this is how the array looks when stored in LS.
{"creator":"dgfdxsf","note":"dsgdsg"},{"creator":"sfs","note":"asd"}
How can I retrieve the values back into an object so that I can display each creator and note associated with that creator ?
Create an object of the values you get from the form.
var obj = {
creator : note
}
Now store this object in the local storage by stringifying in the same as you are doing (JSON.stringify). While retrieving, do a JSON.parse to retrieve the object.
If you have multiple objects like these, push them into an array and store that array in the local storage.
There is no need to convert a string to a JSON string, so you can play with your data without the need for stringify() and parse(). If you save the notes as array, however, you will need to do that.
// Add Note to Local Storage
function addNoteLocalStorage(){
//get saved notes. Set notes to empty string if it's the first time.
let notes = localStorage.getItem('notes') || '';
console.log("Notes return: "+notes);
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
let consolidatedNotesString = creator+":"+note;
//append the new note to the existing note
notes += '\n'+ consolidatedNotesString;
//store the new note
localStorage.setItem('notes', notes);
}
With your edited question, you're saving notes in the form of array of objects, in which case you will of course need to stringify and parse back the notes. One issue with your current code is that you're converting to string the objects(notes) but you save the array which contains the notes as it is. stringify the whole array instead and that's enough. And the way you access the stored notes is by the getItem method and parse it to get back the array. Make sure to save the empty objArray as notes in the local storage before calling addNoteLocalStorage function though, or you will need to check if notes are already in the storage before trying to parse it.
const objArray = [];
localStorage.setItem('notes', JSON.stringify(objArray));
function addNoteLocalStorage(){
objArray = JSON.parse(localStorage.getItem('notes'));
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
//push the string to the Object Array
objArray.push({creator, note});
//store the new note
localStorage.setItem('notes', JSON.stringify(objArray));
}
//And to get the first note and creator for example, you write like:
let noteArray = JSON.parse(localStorage.getItem('notes'));
let firstNoteCreator = noteArray[0].creator;
let firstNote = noteArray[0].note;

How to Store Uint8array in the browser with localstorage using javascript

I've 16 bytes data I'm storing in Uint8Array. I need to store this data in the browser and must get it in some other class.
so my code looks like this:
const ivBytes = window.crypto.getRandomValues(new Uint8Array(16));
localStorage.setItem("iv",JSON.stringify(ivBytes))
console.log("content of ivBytes:" + ivBytes)
and in other class I try to get data like this but it doesnt work
let array = JSON.parse(localStorage.getItem("iv"))
console.log("the iv value we get is: " + ivBytes)
but when I try to get the content of array, it doesnt give me exactly the content of the ivBytes. the output is as follows:
How can I store Uint8array in browser and get it the same way in other class using localStorage? thanks in advance.
It's tough...
An Uint8Array is just a view over an ArrayBuffer which is binary data held in memory.
So my normal advice would be don't store binary data in localStorage, because localStorage can only store strings and that there are other storage APIs that can handle binary data, such as IndexedDB.
But, here what you want to store seems to only be the randomly generated numbers you got from the crypto API, and since it's a really small ArrayBuffer we're talking about, then...
To stringify your TypedArray so that it can be stored in localStorage, you'll need to extract all the values one by one and move them to an Array, or, if available, simply call Array.from(yourTypedArray) and then stringify this Array:
const typedArray = new Uint8Array(16);
crypto.getRandomValues(typedArray);
const arr = Array.from // if available
? Array.from(typedArray) // use Array#from
: [].map.call(typedArray, (v => v)); // otherwise map()
// now stringify
const str = JSON.stringify(arr);
console.log(str);
// localStorage.setItem('foo', str);
// and to retrieve it...
// const str = localStorage.getItem('foo');
const retrievedArr = JSON.parse(str);
const retrievedTypedArray = new Uint8Array(retrievedArr);
console.log(retrievedTypedArray.byteLength);

Can a localStorage value be an object or array?

I am trying to set storage in the user's computer with localStorage("save","{teams:5, points:20}, etc. But I'm not sure if the value can be an object. I've checked the internet, but I can't seem to find clear answers there.
var data={
teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage ("save", data);
Thoughts?
No, the key and value must be a DOMString. See https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem
What you can do is serialise your data as JSON before setting it
localStorage.setItem('save', JSON.stringify(data))
When reading the value, you can parse it back into an object
let saveData = JSON.parse(localStorage.getItem('save'))
local storage limited to handle only string key/value pairs you can do like below using JSON.stringify and while getting value JSON.parse
var testObject = { {name:"test", time:"Date 2017-02-03T08:38:04.449Z"} };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
No, localstorage takes string as and saves it. If you want to save any object then convert it on string and then save it.
while fetching it from local storage you we get string. you may easily covert it into object.
if you directly save an object into localStorage then it will be saved in such manner "[object Object]" and while fetching it from localStorage, you will get "[object Object]" as String.
Wrong Code:
var data={teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage.setItem("save", data);
localStorage.getItem("save")
you will get "[object Object]"
Right Code:
var data={teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage.setItem("save",JSON.stringify(data));
localStorage.getItem("save")
While fetching value from localStorage
Wrong Code:
localStorage.getItem("save")
It will fetch data in form of string.
Right Code:
JSON.parse(localStorage.getItem("save"))
It will return data in form of object.
I hope the solution is well explained.
No, It can't be but you can use stringify. For example:
localStorage.setItem('user', JSON.stringify(r.user));
You need to use the localStorage.setItem(keyName, keyValue);
For Storing a Object, you can make use of JSON.stringify(object) which converts the object to a string.
From MDN
keyName
A DOMString containing the name of the key you want to
create/update.
keyValue
A DOMString containing the value you want to
give the key you are creating/updating.

How to access values from keys from Local Storage in AngularJs?

I want to access the values from some keys in my Local Storage in the most easiest way with AngularJs.
In Resources --> Local Storage I have:
Key:myKey
Value:{ "layouts":[ other_things ],"states":{ other_things },"storageHash":"fs4df4d51"}
I tried:
console.log($window.localStorage.key(0).valueOf('layouts'));
//or
console.log($window.localStorage.getItem('myKey'));
RESULT
myKey
You can do:
$window.localStorage['myKey']
If the data is of stringified(read: JSON.stringify) then:
angular.fromJson($window.localStorage['myKey']);
LocalStorage stores values in strings, not objects. You will need to serialize your object before assigning it and deserialize it when fetching.
var myObject= { "layouts":[ other_things ],"states":{ other_things },"storageHash":"fs4df4d51"};
// Stringify JSON object before storing
localStorage.setItem('myKey', JSON.stringify(myObject));
// Retrieve the object
var myRetrievedObject = JSON.parse(localStorage.getItem('testObject'));
From local storage you get JSON data, so you need to parse it to JS object,
JSON.parse($window.localStorage.myKey).layouts

Categories

Resources