Can you save something in LocalStorage with a variable? - javascript

So this is a quick question, but I was unable to find an answer anywhere.
I know to save things in localStorage you write like this:
localStorage.name = JSON.stringify("this has now been saved under name);
But I want to be able to change what it is saved under depening on a variable, like this:
const banana = potato
localStorage.banana = JSON.stringify("this has now been saved under potato");
Is this possible to do? :)
​​​​​​​

Localstorage allows for the storage of key and value pairs where the value is a string.
If you are assigning to localstorage from reference to another variable, if it resolves to a string then that will work:
const potato = "potato";
const banana = potato;
localStorage.setItem(banana, "this has now been saved under potato");
Otherwise you will need to stringify the value of the variable first.
https://www.w3schools.com/html/html5_webstorage.asp

You can set variables in localStorage with dynamic keys like
const banana = potato
localStorage.setItem(banana, "this has now been saved under potato")

You can add data to your localstorage. You have an key and a value,both need to be strings.
window.localStorage.setItem('myCat', 'Tom');
and you can get it like this:
window.localStorage.getItem("myCat");
To store an variable, array, object etc. you will need to convert it to an string first like this for example:
let arr = [1, 2, 3];
//you need to convert this array to an string.
let arr_string = JSON.stringify(arr);
//now you can store it in your local storage
window.localStorage.setItem("myArray", arr_string);
//to get the array you will need to parse it back from string to array.
let arr_string = window.localStorage.getItem("myArray");
let arr = JSON.parse(arr_string);
console.log(arr); // output: [1, 2, 3]

Related

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.

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;

Why does my push function store my data in a nested manner?

I am working on updating my localStorage to store specific data after every transaction made by the client user. I noticed that my code saves the data in a nested format. This is not desirable.
What would be desirable is if the data is stored in un-nested format.
Find attached descriptive images, to give you a clearer idea of what I mean.
How do I formulate my code to save these data in NON nested manner?
Find below my code
var newData = {}; var transactionDataRetrieved = [];
newData.TransactionTime= "Thu 20:11",
newData.amount= "15,000",
newData.payersNumber= "070505788",
newData.transactionNumber= "PSC999",
newData.waitersName= "Agnes Johnsson!"
transactionDataRetrieved.push({newData: newData});
transactionDataRetrieved.push(JSON.parse(localStorage.getItem('transactionData')));
localStorage.setItem('transactionData', JSON.stringify(transactionDataRetrieved));
The problem is that you are pushing the old value onto a new array every time and then saving it back. Here's one (untested) alternative, adding the newest data to the end. It wouldn't be hard to modify it to put that data at the beginning.
var transactionDataRetrieved = JSON.parse(localStorage.getItem('transactionData') || '[]');
var newData = {};
newData.TransactionTime = "Thu 20:11",
// ...
transactionDataRetrieved.push(newData);
localStorage.setItem('transactionData', JSON.stringify(transactionDataRetrieved));
Or in a single expression:
localStorage .setItem ('transactionData', JSON .stringify (
(JSON.parse (localStorage .getItem ('transactionData') || '[]') .concat (newData)
))
You are pushing array to array
// pushing object to array
transactionDataRetrieved.push({newData: newData});
// pushing array to array
// localStorage.getItem('transactionData') returns array
// because you created, var transactionDataRetrieved = []; as array
transactionDataRetrieved.push(JSON.parse(localStorage.getItem('transactionData')));
localStorage.setItem('transactionData', JSON.stringify(transactionDataRetrieved));
What you should be doing
transactionDataRetrieved.push({newData: newData});
// changed push to concat
var newArray = transactionDataRetrieved.concat(JSON.parse(localStorage.getItem('transactionData')));
localStorage.setItem('transactionData', JSON.stringify(newArray));
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
There are some minor issues with your code that I want edit check it:
var newData = {};
newData.TransactionTime= "Thu 20:11",
newData.amount= "15,000",
newData.payersNumber= "070505788",
newData.transactionNumber= "PSC999",
newData.waitersName= "Agnes Johnsson!"
// **newData** is already an Object so don't wrap it in an object
//First get data from the localStorage;
//store it in array of Objects
var transactionDataRetrieved = localStorage.getItem('transactionData');
transactionDataRetrieved.push(newData);
//Now set this array in local storage
localStorage.setItem('transactionData', transactionDataRetrieved);

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

Store object from local storage into variable

I am trying to retrieve a object from localstorage and trying to load it into a variable . How can i do this ? This is where i m stuck
var messageStorage={};
messageStorage.retrieve = function () {
var storageString = localStorage.getItem(credentials.mobileNumber);
var storageObj = JSON.parse(storageString);
// whats should go here for messageStorage to be equal to storageObj
};
On messageStorage.retrieve(); the variable messageStorage must contain the value from localstorage.
with localStorage the data is actually stored as a string.
And you use JSON.parse to return the value
JSON.parse() Returns the Object corresponding to the given JSON text.
Example :
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
But i saw that you want to return the variable. So what's the type of this variable ? Number, String, Boolean ? You can convert from String to what you need
localStorage allows you to save only strings, so if you have to save an object you should save it as a JSON string or you can use this library to solve your issue
first of all we can't store objects to localstorage, only strings are allowed:
localStorage.setItem("test", JSON.stringify(jsondata));
var item = JSON.parse(localStorage.getItem("test"));
now you have json data to parse it and get the value.

Categories

Resources