Set data from localStorage when user is connected - javascript

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;

Related

Local Storage display problems

i'm trying to use localstorage to append recent city searches from user to a form element.
The problem is now im very unsure of how to progress further if .innerHTML wipes out all text
when it's putting anything into the element. the end goal would be for the form element to look something like
athens
paris
chicago
any ideas on how to implement this?
new to local storage so would appreciate any help
here's an example of the code :)
// HTML
<form class="recent-search" id="demo"></form>
// JAVASCRIPT
function setStorage() {
// here i'm trying to store nameValue to localstorage
localStorage.setItem('', nameValue);
}
setStorage()
function getValue() {
// now i'm getting nameofcity from localstorage
return localStorage.getItem('nameofcity');
}
// console logging it so i can make sure it's working (it is)
console.log(getValue());
function myFunction() {
// now i set the innerHTML of the element with the ID of "demo" to be "1. "nameofcity"
document.getElementById("demo").innerHTML = '1. ' + localStorage.getItem('nameofcity');
}
myFunction();
if you'd like more context heres the github repository https://github.com/LukeMcHenry311/Server-Side-Weather
You're saving the value to the key of an empty string and then trying to retrieve the key of nameofcity, which you probably didn't save it to. localStorage works by key-value pairs. You can always go to your browser's dev tools (usually by hitting F12), and under Application tab you can see what's in your local storage
It should be something like
function setStorage() {
localStorage.setItem('nameofcity', nameValue);
}

Retrieving data objects from localstorage and reload them into array

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

Html Storage resets every refresh, initialize function not working

For a website I am working on, I am trying to keep information on how many items you buy to be shown across html pages. Researching how to do this has led me to believe that Html sessionStorage is the best way to do this (if there is a better/easier way please let me know). Yet, whenever I refresh the html page or go to another page the data resets.
Here is my code:
function initialize(name, val) {
if(localStorage.getItem(name) === null) {
localStorage.setItem(name, val);
}
}
initialize("subCost", 0);
initialize("quantity", 0);
initialize("hasProduct", false);
Then since the storage only stores strings, I convert these into integers and boolean
var $quantity = parseInt(localStorage.quantity);
var $subCost = parseInt(localStorage.subCost);
var $hasProduct = localStorage.hasProduct == "true";
Before without the initialize function, I made the local storages items like this
localStorage.setItem("subCost", 0);
localStorage.setItem("quantity", 0);
localStorage.setItem("hasProduct", false);
and still converted these into those variable but they never saved with each refresh. How do I get these to save changes I make to them with each refresh.
The .setItem() method on localStorage doesn't only "sets" a "memory placeholder" for a value... It also overwrites it, if it already exist.
To save the user generated values, the best "moment" to save a "change" is the change event.
Use the same .setItem() method as in your initialize() function.
$("input").on("change",function(){
// Get id and value.
var id = $(this).attr("id");
var value = $(this).val();
// Save!
localStorage.setItem(id,value);
});
CodePen
Just as a hint...
This method to save values locally is ephemeral...
Values are kept until user closes the browser.
Not just closing the page, but closing the browser completely.
So to keep some values between pages navigated, this is the optimal use.
To store values for a longer run (like 6 months or longer), use cookies.
Have a look at jQuery Cookie plugin.

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].

Making an Array Variable Global in JavaScript

I'm setting a an array variable to 0 on load of my javascript.
var postArray= new Array();
However, I used this array to hold my objects that I retrieve from localStorage. It works when I upload more blog posts that get entered into localStorage and displays. However, after I refresh the page this is called again as is an empty array and say I go to enter my 3rd blog post after i've refreshed, my localStorage is set to only having the contents of my postArray. Therefore, I'm clearing out my localStorage when I dont want to.
if you throw it into an if statement, postArray is undefined.
if (localStorage.getItem("posts") === null) {
var postArray = new Array();
}
I'm trying to make the postArray global at the start yet only create a new array when localStorage is empty.
You should just get the content from the localStorage, and if it's empty, then return an empty array.
For example.
var postArray= getPosts();
function getPosts() {
var posts = localStorage.getItem("posts");
return posts ? JSON.parse(posts) : [];
}
i think you should use document coockie instead of array !!
when page is load read the cookie content if it's empty "localStorage" then store the "whatEver you want" value on its ! this is better than arrays

Categories

Resources