Reputation: 6986
I am working with LocalStorage for the first times for a web app I am working on. However I have hit upon a problem that I hope someone will be able to help me with,
Using localStorage I am saving a JSON object too it. This JSON object gives somewhere to store data and pull data from to drive my web app, without the need for a database connection of LAMP server. So is the ideal solution for.
On the web app start the user makes some choices that drive what JSON files the app uses to startup with the code for this is here,
makeSelection: function(element) {
var that = this;
element.parents('.column-wrapper').find(".selected").removeClass("selected");
element.addClass("selected");
if(element.data("collection") != undefined) {
$.getJSON('json/' + element.data("collection") + '.json', function(data){
localStorage.setItem('collection', JSON.stringify(data));
});
}
if(element.data("room") != undefined) {
localStorage.getItem('room');
}
}
Now the above code works fine, if I console.log(localStorage.getItem('collection')
then I get
{collection: "{"name":"Default JSON 1"}"}
which I would expect, however at any point the user can change where their data comes from meaning running the makeSelection
function again. The user then for example selects default JSON 2, I check the network tab, and see that the request has been made for that JSON file, and the JSON has been returned.
I run console.log(localStorage.getItem('collection')
again expecting to get
{collection: "{"name":"Default JSON 2"}"}
as I requested that JSON file, and I can that JSON as the response in my network tab, however what I get in my console is still,
{collection: "{"name":"Default JSON 1"}"}
Should running makeSelection()
not change the collection item in localStorage to match that of the getJSON
response?
Am I missing a step, or using localStorage incorrectly?
Upvotes: 0
Views: 4892
Reputation: 25629
The only explanation is that your callback is not being triggered.
localStorage.setItem('collection', 'data 1'); (function () { return localStorage.getItem('collection');})();
> "data 1"
localStorage.setItem('collection', 'data 2'); (function () { return localStorage.getItem('collection');})();
> "data 2"
Have you tried doing some debugging? Such as
if(element.data("collection") != undefined) {
$.getJSON('json/' + element.data("collection") + '.json', function(data){
console.log('CAME INTO CALLBACK');
localStorage.setItem('collection', JSON.stringify(data));
console.log('FINISHING CALLBACK');
});
My guess is that you'll see neither of those prints in the console when you run your code.
Upvotes: 2