Reputation: 53
I want to save an object to local storage as a JSON string for offline rendering. Only desire write function at this time for testing. My question is why is only one key/value string (array) writing to localStorage?
Here is the object I'm trying to save.
Addr_states
-JhMZ6QjAm0FRAcRjivP
Country:
State:
-JhMdqTXuayd00hqkp_E
Country:
State:
-JhMgVVy_58upfBjf0sO
Country:
State:
-JhMjte-ujgsmxgyX8Zf
Country:
State:
-JhMkPrScGjvRNVna4Hp
Country:
State:
-JhOYj6j4lW4Y38wJDsN
Country:
State:
And here's my code so far:
function myDataStore (myDataPass)
{localStorage.setItem("States", JSON.stringify(myDataPass));}
if (myStorageStatus == true)
{
if (myOnlineStatus == false)
{
myDataSource = "Local Storage";
}
else
{
myDataSource = "Web Firebase";
localStorage.removeItem("States");
var myDataRead = new Firebase('https://myappURL/Addr_states');
myDataRead.on('child_added', function(snapshot) {
myDataGroup = snapshot.val();
console.log(myDataGroup);
myDataStore (myDataGroup);
});
}
}
When pulling cast of the variable myDataGroup
into the snapshot function, I get the last key/value array as a string without the key (seen in object above) or meta data for last update. Outside the function, the result appears (within the developer console) as an empty object.
myDataGroup
was declared at top of the code block, outside the scope of the function.
Changed to add code suggested from commenter below - produces single string (array) last one in States - this - {"Country":"USA","State":"Utah"}
Upvotes: 2
Views: 3112
Reputation: 599736
Your code is responding to child_added
events:
var myDataRead = new Firebase('https://myappURL/Addr_states');
myDataRead.on('child_added', function(snapshot) {
A child_added
event fires for every child that is added under the indicated node. So in your case: a child_added
event is fired for every state.
That also means that your callback function is invoked for every state. And you then overwrite whatever was in local storage with the information for that state:
myDataStore (myDataGroup);
So essentially your local storage will now contain whatever the last state was that came from Firebase.
Given that you named your local storage States
, it seems like you want to store all states in there. This can be most easily accomplished by listening for Firebase's value
event:
var myDataRead = new Firebase('https://myappURL/Addr_states');
myDataRead.on('value', function(snapshot) {
myDataGroup = snapshot.val();
console.log(myDataGroup);
myDataStore (myDataGroup);
});
If you also want to loop over the individual states, you can use forEach
:
var myDataRead = new Firebase('https://myappURL/Addr_states');
myDataRead.on('value', function(allStates) {
allStates.forEach(function(stateSnapshot) {
console.log(stateSnapshot.val());
});
});
Upvotes: 4