Thuesmann
Thuesmann

Reputation: 1

How to update Firebase multiple times

so when trying to go through a loop that checks, updates, and posts data to my Firebase storage, it seems that whenever I try to use the Firebase.update(), then it messes with my for loop and it repeats incrementations or doesn't increment at all. Any advice?

My Code:

var j = 0;
    var k = 0;
    var l = 0;
    var m = 0;
    var setDict = {};
    for(var h = 0; h < teamWinNames.length; h++)
    {
        console.log(j);
        console.log(h);
        console.log(meWinList[j]);
        var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
        var tempName = teamWinNames[h];
        tempRef.once("value", function (teamWinSnapshot)
        {
            var exists = teamWinSnapshot.child(meWinList[j] + '/' + tempName).exists();
            console.log(exists);
            if(exists == true)                  
            {
                console.log("Here");
                var tempVal = teamWinSnapshot.child(meWinList[j] + '/' + tempName).val();
                console.log(tempVal);
                //var tempValue = obj[tempname][tempchamp];
                //console.log(tempValue);
            }
            else
            {
                setDict[tempName] = '1-0-0-0';
                console.log(setDict);
            }

        });
        if(h != 0 && (h+1)%4 == 0)
        {
            sendUpdate(setDict, meWinList[j], username);
            setDict = {};
            j++;
        }
    }

and the function that makes the update:

function sendUpdate(data, champ, username)
{
    var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
    tempRef.child(champ).update(data);
}

Upvotes: 0

Views: 707

Answers (1)

Andr&#233; Kool
Andr&#233; Kool

Reputation: 4968

The problem is that you are getting your data in the for loop and also changing it inside the loop. This means that the data you are using in your loop changes with each iteration. And as an added bonus you get the effects of the asynchronous nature of firebase that can look something like this:

  • Get data (1)
  • Get data (2)
  • Update data (1)
  • Get data (3)
  • Update data (3)
  • Update data (2)

To prevent all this i suggest putting the for loop inside the tempRef.once function like this: (pseudo code)

tempRef.once{
    Loop through data{
        Change data
    }
    Update data
}

This means you only have to get the data once and update it once.

Upvotes: 1

Related Questions