Retrieving data objects from localstorage and reload them into array - javascript

I have taken some key points from this site already when it comes to transferring data to and from local storage. However, it does not seem to work properly. In short, I am trying to load data in the form of an array containing objects, to and from the local storage. I am aware that it is saved as a string within local storage and have then used JSON formatting to solve that problem, it is also where I think the problem might be when there is objects within objects. However, in its current state, it does not seem to work. Any ideas?
var students = [{name: "Petrina", age: "20"}];
function saveList(){
localStorage.setItem('somekey', JSON.stringify(students));
console.log("Saved to Local");
}
function loadList(){
students = JSON.parse(localStorage.getItem('somekey'));
}
The code gives no errors, I am using the functions in relation to loading the window.
window.onload = () => { loadList() }

You've added that you are calling from onload, and,
in your code you are loading into students.
add to the beginning of your code:
var students;.
Note: Some Objects need special handling.
For example: Date:
var date = new Date();
localStorage.date = JSON.stringify(date);
date = new Date(JSON.parse(localStorage.date));
Answer before additional information:
key is a method of localStorage.
Don't use it.
Use students instead, for example.
Storage.key()
(This is assuming that you call the functions)
var students = [{name: "Petrina", age: "20"}];
function saveToLocalStorage(key, value){
localStorage.setItem(key, JSON.stringify(value));
console.log("Saved to LocalStorage");
}
function loadFromLocalStorage(key){
console.log("Loaded from LocalStorage");
return JSON.parse(localStorage.getItem(key));
}
console.log("students: "+students);
saveToLocalStorage("stu", students);
var st2=loadFromLocalStorage("stu");
console.log("st2: "+st2);
cannot be run in a snippet: sandboxed, no access to localStorage - cross origin.

It got solved! - I am unsure what the problem was. I cleared all the calls for all functions and debugged the save and load function 1 at a time whilst watching the local storage data. The problem to begin with was that it simply did not save the data that got updated during runtime, hence it just kept loading values that always were the same. #iAmOren's idea by creating a function that returns a value might have done it, however I am unsure why. Thanks for the responses & Support!

Are you missing a call to your saveList function?
Calling saveList before calling loadList works as you expect.
Please refer: https://codesandbox.io/s/strange-brown-3mmeq?file=/index.html

Related

How to update object value in local storage

I'm in the middle of creating a simple tv shows tracker (which ones I have seen/watching at this moment) and as I don't backend myself, I decided to store all the data in local storage.
Right now I'm able to store all the shows in the local storage with no problem. The problem occurs when I need to update data in local storage (to give you a specific example - please look at the screen below):
screenshot of my list with local storage shown
As you can see I have those buttons to adjust the number of show's seasons and episodes (they work just fine).
But I have no idea how to store that updated value and that value only in local storage.
Down below you can find the code that reads data from local storage and use them to create list:
function readFromMemory(){
const data = JSON.parse(localStorage.getItem('seriale'));
data.forEach(element => {
serialeMemory.push(element);
let serialInMemory = new SerialeList(element.pos, element.img, element.name, element.score, element.userEpisodes, element.episodes,element.userSeasons, element.seasons, element.status, element.id);
serialInMemory.inject(); //Creates list from class
serialInMemory.episodeUpDown(); //Gives functionality to episodes buttons
serialInMemory.seasonUpDown(); //Give functionality to seasons buttons
});
deleteSerialRow(); //method to delete the whole row from list and from local storage
}
I know how to filter out to show only what I want by using Array.prototype.filter method. But I don't know how to push only that row into localstorage.
I would very gladly appreciate any insight.
Thank you.
Well, since you only use one key („seriale”), there's no other way as to deserialise it, modify the object accordingly (e.g. using Array.prototype.splice), serialise it again and call localStorage.setItem with the same key and the updated and serialised object.
To be honest I kinda solved it myself.
Here's the method that works:
updateSeasons(id, changeValue){
const data = JSON.parse(localStorage.getItem('seriale'));
const filter = data.filter(element => element.id === id);
filter[0].userSeasons = changeValue;
for(let i = 0; i< serialeMemory.length; i++){
if(serialeMemory[i].id === filter[0].id) serialeMemory[i].userSeasons = changeValue;
}
localStorage.setItem('seriale', JSON.stringify(serialeMemory));
}
I've used the very same array I have kept pushing during the DOMLoad event and it works just fine.
But yeah, I probably should have attach a key to every single show, but I think I'm fine with my solution. Thank you anyway!

Storing a HTML OBJECT Array inside Chrome Storage for a Chrome Extension

BACKGROUND:
I'm writing a chrome extension that when you access a certain page it finds all the table rows and then stores them and when you go back it shows you all the new values that have been added.
I want to store an array in storage so that when the user comes back to the page I can access it. Mainly to compare results each time to see if anything has changed.
Example.
myArray = [HTML OBJECT, HTML OBJECT, HTML OBJECT];
on.window.unload {
Chrome.storage.set(STORE MY ARRAY)
}
on.windows.onload {
chrome.storage.get(MY STORED ARRAY AND SET TO OLD_myArray[])
}
function compareArrays() {
TO DO STUFF WITH MY myArray[] and OLD_myArray[]
e.g. comparing values to see if anything has changed.
}
I've tried local Storage but realised that It doesn't store arrays, So moved to Chrome storage.
I would like help getting myArray to store itself on unload and then set itself to OLD_myArray onload, So I can compare the values for the differences. Thanks.
In order to use chrome.storage, you need to use one of two methods:
chrome.storage.sync, which syncs saved data to any browser the user logs into.
chrome.storage.local, which only saves data to the current machine.
As the official documentation discusses, chrome.storage is implemented with callbacks, not with a return value from the get or set call itself.
// Save the current myArray value.
chrome.storage.local.set({'storedArray': myArray}, function() {
console.log(`storedArray now contains ${myArray}.`);
});
// Retrieve the the stored value, defaulting to an empty array.
chrome.storage.local.get({'storedArray': []}, function(data) {
console.log(`storedArray's value is ${data.storedArray}.`);
});
As an aside, it may not be a great idea to attach storage functions to an unload event, as the browsing context could terminate before the operation is complete. A browser crash, for instance, wouldn't call the window.unload event (this is only one of a number of situations which would interfere with your handler).

Set data from localStorage when user is connected

I have been working on a save file for my game. The save file IS working, and console.log displays proper values:
function saveGame(){
localStorage.setItem('game', JSON.stringify(game));
}
function loadGame(){
var retrievedObject = localStorage.getItem('game');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
}
Image of the logs: https://s28.postimg.org/bslusmagt/Untitled.png
I'm still new to all this as I have started learning JS couple of months ago. Right now my guess is that when the page is loaded, I'm supposed to set all these values. Trying the next thing i get "null" in console.log
console.log(JSON.parse(localStorage.getItem('game.plutonium')));
I thought values could be set something like:
game.plutonium = localStorage.getItem('game.plutonium');
But it doesn't work. Whats the trick here?
Here is my full JS code, just in case: http://pastebin.com/yM2wz410
Values are defined from line 1, and save / load file is on the line 350-356.
Why doesn't my method work?
function saveGame(){
var savefile = JSON.stringify(game);
localStorage.setItem("game", savefile);
}
function loadGame(){
var savefile = localStorage.getItem("game");
if (savefile === null) {
return;
}
game = JSON.parse(savefile);
}
Method above seems to have completely solved the problem. Thanks :)
JSON.stringify() changes the object you give it into a string (which can be stored very easily). But: you can't navigate that string anymore via string.key
To translate that json string back into a object (that can be navigated again), you need to use JSON.parse().
Your problem above is, that you store the whole object (as json) into the storage with key game and then try to get the item game.plutonium from the storage. Note that you didn't save anything as game.plutonium.
You need to first fetch the whole json string via localStorage.getItem('game'), then parse the string back to an object and only then you can navigate over it again like game.plutonium.
var game = JSON.parse(localStorage.getItem('game'))
var plutonium = game.plutonium;

Create object and add to array of pointers - always replaces existing array

I have probably misunderstood the documentation somehow but cannot figure this out.
What I want to do, is to be able to create a new ClientContact and save it to an array of pointers called contacts in Clients table.
This is the relevant code:
var Client = Parse.Object.extend("Client");
var selectedClient = new Client();
// sets the objectId based on URL params
selectedClient.id = $routeSegment.$routeParams.id;
var ClientContact = Parse.Object.extend("ClientContact");
var contact = new ClientContact();
contact.set('name', 'test');
contact.set('desc', 'some description');
contact.set('phoneNumber', '123');
selectedClient.add('contacts', contact);
selectedClient.save().then(function() {
console.log('saved');
}, function(error) {
console.error(error);
});
As expected, the contact is automatically saved and added to contacts when the selectedClient is saved.
But if I run the same code again (in the testing this means refreshing the page), a new ClientContact is saved but it replaces the contacts array entirely.
That is, only the most recent ClientContact is associated to the Client, any new additions replaces the array, leaving only one pointer.
I hope there is an obvious an easy fix that I have simply failed to spot.
Ok seems I have located the problem.
I was assuming that array operations on an object was independant on the local representation.
What I did above was to construct an object based on a known objectId:
var Client = Parse.Object.extend("Client");
var selectedClient = new Client();
// sets the objectId based on URL params
selectedClient.id = $routeSegment.$routeParams.id;
Turns out that array operations like add and remove are performed based on the local information. So doing the above construction leaves my array, in the selectedClient object, empty at each page refresh. This was the cause of my array being replaced with a new single valued array.
In short, one should fetch an object before performing array operations it seems.
The reason for the construction above was to avoid having to re-query the Client object when navigating around an AngularJS based webpage. The solution was fortunately simple: loading the Client object once in a parent scope.
This moves outside the scope of the question. Just wanted to mention that as well.

html5 localstorage not working the way I want

I am using HTML5's localstorage to save two variables and load them when the user refreshes the page but something doesn't work properly when loading the saved item:
var's:
var cookies = 0;
var cursors = 0;
saving code:
window.setInterval(function(){
var save = [cookies, cursors];
localStorage["save"] = JSON.stringify(save);
console.log("Saved game");
}, 1000);
loading code:
function load() {
var state = JSON.parse(localStorage["save"]);
console.log("Loaded game");
}
What my console show's on page load:
[13,1]
Loaded game
[0,0]
Saved game
[0,0]
Saved game
[0,0]
Saved game
Etc.
The load() function gets called on body load (<body onload="load()">
and I DO get the console message "Loaded game"...
You syntax seems fine. However, JSLint recommends using dot notation on localStorage:
localStorage.save = JSON.stringify(save);
and
var state = JSON.parse(localStorage.save);
Then you can just add your state variable to the console.log statement to check it:
console.log("Loaded game: "+state);
Remember, your values have been saved as an array, so you'll have to access them with state[0] and state[1] to get the individual values.
There is nothing wrong with your localStorage access. Also, you don't need to try sessionStorage if is localStorage what you are looking for.
The problem, I think, is with how are you dealing with your data.
Judging by your code, you are reading the localStorage data and storing it into a local variable called state and doing nothing more with it.
Fact: if you are REALLY getting to save your data to localStorage with the
localStorage["save"] = JSON.stringify(save);
then the
var state = JSON.parse(localStorage["save"]);
would actually work, if performed anytime after the previous snippet. So, if your application is actually getting to run the snippet where you save the data, then later when you run the load function, the local variable state will have the content [0, 0].

Categories

Resources