Natedog
Natedog

Reputation: 53

Firebase to localStorage

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?

What I've tried

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);
        });


    }
}

Notes

Upvotes: 2

Views: 3112

Answers (1)

Frank van Puffelen
Frank van Puffelen

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

Related Questions