Store JSON to localstorage not working - javascript

After pushing a button I would like to save an item (nested JSON) into a new Array and store it to the localstorage.
addFavourite(card) {
console.log(JSON.stringify(card));
var cards = [];
this.cardfavouriteArray.push.apply(cards, card)
this.storage.set('favouriteData', this.cardfavouriteArray);
}
getData() {
var data = this.storage.get('favouriteData');
if(data){
this.storage.get('favouriteData').then((val) => {
console.log('test', JSON.stringify(val));
});
}
I get no error, but 'test' is always empty. I need it as an array.

Set and Get method for localstorage varies on which service you are using
1.HTML5 localStorage- If you are using HTML5 localStorage directly then you should use localStorage.getItem
and localStorage.setItem
2.localstorage is limited to store only string key/value pairs.Use JSON.stringify and JSON.parse when using setting and getting from localstorage
addFavourite(card) {
console.log(JSON.stringify(card));
var cards = [];
this.cardfavouriteArray.push.apply(cards, card)
this.storage.setItem('favouriteData', JSON.stringify(this.cardfavouriteArray));
}
getData() {
var data = this.storage.get('favouriteData');
if(data){
this.storage.getItem('favouriteData').then((val) => {
console.log('test', JSON.parse(val));
});
}
3.ng2-webstorage- In case of ng2-webstorage this.storage.retrieve and this.storage.store will work.

Change this.storage.set('favouriteData', this.cardfavouriteArray); to localStorage.set('favouriteData', JSON.stringify(this.cardfavouriteArray)); (It's a pre-defined method by angular). Also stringify the array.

Set array in local storage like this:
localStorage.setItem('favouriteData', JSON.stringify(this.cardfavouriteArray));
Get array from local storage like this:
var data = JSON.parse(localStorage.getItem('favouriteData'));
Explanation: It is because localstorage can not store object, it stores in string format. So we need to JSON.stringify the object. Also localStorage has function name setItem and getItem as defined here: http://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage. When we get the string from localstorage, we need to JSON.parse to convert it back to object.
You are using this.storage.set and this.storage.get. It is not clear which library are you using, but the code I mentioned will work in Angular or any framework. Since localStorage.setItem and localStorage.getItem is pure javascript.

Related

Why the getItem method of Local Storage object has been used before setItem in following JS code?

https://github.com/john-smilga/javascript-basic-projects/blob/master/14-grocery-bud/final/app.js#L6
The following code has been written from the above link. Full Version of this code is in the link. My question is why getItem method is used before setting Item and what is the logic the behind this?
Thanks.
function addToLocalStorage(id, value) {
const grocery = { id, value };
let items = getLocalStorage();
items.push(grocery);
localStorage.setItem("list", JSON.stringify(items));
}
function getLocalStorage() {
return localStorage.getItem("list")
? JSON.parse(localStorage.getItem("list"))
: [];
}
``
Because the intent behind the code is to add an item to an array in localstorage. You fetch the array, or create a new one if it doesn't exist. You push an item onto it and then save it back to localstorage.

Unable to store the state of an array inside map - Reactjs

I am working on reactjs project where i have to store the array value in a local variable that i am parsing form a JSON data . I am successfully able to parse the data using map function , i want to store the result data in a global array , but i am unable to declare state inside map function, how do can i get access to the array which i am retrieving through map. below is my code.
//post data input
let postData = { Userid: this.props.Userid };
//post data is a method which return's the json array its a post request
PostData('UserDetails', postData).then((result) => {
//storing the data in a variable
responseJson = result;
{
//parsing the json using map
responseJson.Jiralist.map((rowdata, i) => (
// i want to store this value in a global array
console.log("", rowdata.jirakey);
))
}
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
If dont really need to modify the existing array, you can use forEach.
And create a global array and push the new item using spread operator
let globalArr = [];
responseJson.Jiralist.forEach((rowdata, i) => ([...globalArr, rowdata.jirakey]))

I have a javascript class and a object for that class and i want to store that object in local storage and retrieve it?

In my program i create a object for every connection and i want to retain those objects even after refreshing the webpage.how can achieve that?
<script>
var ip=prompt("Enter address of printer:", "12.222.170.99");
conn =new connection();
localStorage.setItem(ip,JSON.stringify(conn));
var a=localStorage.getItem(ip);
var b=JSON.parse(a);
b.fun();
function connection()
{
this.fun=function()
{
alert("hi");`enter code here`
}
}
</script>
If you are ok with using a jQuery plugin then you can use
$.cookie("cookie_name", JSON.stringify(json_object))
as shown in the following:
jquery save json data object in cookie
This uses the jQueryCookie plugin.
An Alternative is to use localStorage
// Store the object after you stringify it
localStorage.setItem('name', JSON.stringify(json_object));
// Get the object from storage and parse it back to json
var retrievedObject = JSON.parse(localStorage.getItem('name'));

Chrome Extension: StorageArea.Set key being passed as string

Good evening,
I'm trying to save an associative array into chrome.storage.local, like so:
var keyName = 'name';
var data = //grabbed from an Ajax call
saveData(keyName, data);
function saveData(keyName, data){
console.log("saving with key: "+keyName);
chrome.storage.local.set({keyName:data});
}
To check to make sure the data saved properly, I load:
function loadData(keyName){
console.log("loading: "+keyName);
chrome.storage.local.get(keyName, function(result){
console.log(result);
});
}
The log shows it is trying to load the correct key name, but nothing comes up. I then try calling loadData(null), which will show the entire contents of the local storage, and I find:
Object {keyName: Array[3]}
keyName: Array[3]
__proto__: Object
My data! But the key it saved with is "keyName" instead of "name". The log from saveData outputs that it is "saving with key 'name'", but it's saving with key "keyName" instead...
????
Thanks!
How strange...
Seems my question is similar to Using a variable key in chrome.storage.local.set
The answer they found was to convert the JSON {keyName:data} to an object:
var obj = {};
obj[keyName] = data;
chrome.storage.local.set(obj);
This works.
Is this because the JSON field is automatically passing as a string?

Save Javascript file object to local storage

I have a input type file where I save the file to a file object like so
var uploadControl = document.getElementById("fileUpload");
var files = uploadControl.files[0];
Then I would like to save that file to local storage to read into the FileReader object at a later time. Does anyone know if this is possible. I have tried several different options and every time I try and retrieve the object out of local storage, it is undefined.
Here are some things I have tried
var setObj = {"prop": "myProp", "file": files};
chrome.storage.sync.set({"myObj":setObj});
This doesn't throw errors, but when I try and retrieve the object, it is undefined
chrome.storage.sync.get("myObj", function(item) {
console.log("item name: " + item.myObj.file.name);
});
However I can access the other properties of the object
chrome.storage.sync.get("myObj", function(item) {
console.log("item prop: " + item.myObj.prop);
});
Am I doing something wrong when adding the object to local storage or am I accessing it incorrectly? Or is it just impossible to do this?
localStorage can only contain string name/value pairs, which means you can not store an object directly.You can use stringify and parse for that.

Categories

Resources