VladimirSD
VladimirSD

Reputation: 441

Firebase returning undefined on child added

The following code is running locally in a browser. On page refresh it retrieves the top 2 objects and writes to the console three of the object values.

ref.orderByChild("Timestamp").limitToLast(2).on("child_added", function (snapshot) {           
            var payload = snapshot.val();
            var file = payload.filePayload;
            var timestamp = payload.TimeStamp;
            var sDate = payload.DateString;
            console.log(file);
            console.log(timestamp);
            console.log(sDate);
        });

Something like

ImageOne.jpg
1448683124188
Nov 27, 5:30pm

The issue is when a new entry is made in the database I'm only getting the file name and the other two (timestamp and date) are 'undefined' in the console output.

If I refresh the page then those undefined fields are populated correctly. It's always those two values that are missing. Never file

Upvotes: 0

Views: 545

Answers (1)

VladimirSD
VladimirSD

Reputation: 441

The problem seems to be as soon as you do a "setValue" it writes to the database and notifies the clients. They retrieve the data even though you have more data to write.

I was doing something like:

Firebase newItem = firebase.push();

newItem.child("filePayload").setValue(fileString);
newItem.child("TimeStamp").setValue(ServerValue.TIMESTAMP);
newItem.child("DateString").setValue(now);

As soon as the first setValue happened the client got notified and it got the data, but only filePayload. The other two values were still being written to the db. If the client refreshed then all three values are retrieved.

I changed my code to the following and it now works

Firebase newItem = firebase.push();

Map<String, Object> entry = new HashMap<String, Object>();
entry.put("filePayload", fileString);
entry.put("DateString", now);
entry.put("TimeStamp", ServerValue.TIMESTAMP);

newItem.setValue(entry);

Upvotes: 1

Related Questions