Firebase snapshot reference won't return data - javascript

I'm using firebase and have a list of people, with certain priorities. In one of my functions, setting and getting priorities is working fine. But in another, I can only set and trying to get the priority of the item returns 'dataSnapshot.getPriority() is not a function'.
var playersList = new Firebase('https://myfirebase.firebaseIO.com/players')
var winnerSnapshot = playersList.child(winner);
winnerSnapshot.setPriority('1300'); //This is working
var oldPriority = winnerSnapshot.getPriority(); //Not working

There are actually two different types of object at play here. A Firebase reference, and a DataSnapshot. When you call new Firebase(), you get a Firebase reference which allows you to write data (e.g. using set or setPriority) or attach callbacks for reading data (e.g. using on or once).
These callbacks registered with on() or once() receive the data via a DataSnapshot and you can call .getPriority() on that. Check out the Reading Data docs for full details.
For example, to make your example work, you could do something like:
var winner = "somebody";
var playersListRef = new Firebase('https://myfirebase.firebaseIO.com/players')
var winnerRef = playersListRef.child(winner);
// You use a firebase reference to write data.
winnerRef.setPriority('1300');
// You can also use a firebase reference to attach a callback for reading data.
winnerRef.once('value', function(winnerSnapshot) {
// Inside your callback, you get a DataSnapshot that gives you access to the data.
var priority = winnerSnapshot.getPriority();
});

Related

How to compare value and delete from firebase realtime database?

I am using Firebase realtime database in Android app, and have data like this:
How can I access that data from javascript.
I just wanna code function to get value of every endTime and compare with current time and if endTime <= Current Time then delete values yellow marked on anther image.
Events is fixed value.
Indjija, Vojvodina and -KsB2mVkpgQe_fRyFFH4 are auto generated so it's possible to have more values like that two.
I know how to solve that in android studio with Java code but I'm interesting about implementing server functions.
The answer to this question is buried deep within Firebase Database Reference.
forEach() is used to get to the child without knowing the child's exact path.
var leadsRef = database.ref('leads');
leadsRef.on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
});
});
Now childSnapshot will contain the required data, the same thing can also be accessed using child_added.
leadsRef.on('child_added', function(snapshot) {
//Do something with the data
});
The only difference is that in case of forEach(), it will loop through from the start so if any new data will be added, it will also load the previous data but in case of child_added, the listener is only on new child and not the previous existing childs.
Useful Link:
Firebase Read and Write Web
Hope it helps.

Firebase - Multi-location updates method deprecated, what now?

I had some apps that used the multi-location update method as below:
const updates = [];
updates['/location1'] = data;
updates['/location2'] = data2;
firebase.database().ref().update(updates);
Yet, as I'm developing a new app, I got the following message:
FIREBASE WARNING: Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.
With no real info anywhere about how to perform multi-location atomic updates anywhere, and the docs are still with the old method. Chaining then() is not a good idea, as it would be a nightmare to rollback.
Any clues and/or information on new multi-location updates methods?
I didn't even know you could pass an array. You should instead pass an object:
const updates = {}; // this line is different
updates['/location1'] = data;
updates['/location2'] = data2;
firebase.database().ref().update(updates);
The array syntax we use for setting properties works on a JavaScript object too.

Firebase database on push get id

I am trying to imitate an insertion trigger on Firebase using the onWrite method. The insertion is done via POST requests since I am testing it (easiest way I found to check database triggers). The trigger includes writing the Firebase generated ID inside the inserted data as a new property.
My cloud function is this:
exports.onNewSeries = functions.database.ref('/series').onWrite(event => {
"use strict";
console.log(event.data.key);
console.log(event.data.current.key);
console.log(event.data.current);
});
Both first logs contain the same key (series), which actually is the key of the parent node where the new data is appended, instead of the new data key (in the quirky form of -adfaa123sdfasdf). The last log prints a Firebase structure containing the new data as well as the generated key in a _data property, however it is not accessible.
While this can be done manually after a request, I have not seen it automated in a database trigger way.
To get the generated key, make the function trigger on a specific child:
exports.onNewSeries = functions.database.ref('/series/{id}').onWrite(event => {
console.log(event.params.id);
});
Also see the Firebase documentation on handling database events.

Firebase - Object vs Array and Returning a .key()

I'm using firebase + angularfire for a project that involves multiple users editing data at the same time (which would make an object ideal) as well as the need to quickly sort and filter the data on the fly (ideal for an array).
So, would it be better for me to:
1) use FirebaseObject and then use an angular toArray filter for sorting
2) use FirebaseArray and just make sure to use $add to ensure use of unique IDs (even storing the push ID as a property of the pushed object itself).
Currently, we are using the second option, which leads me to my second question:
When I use $push, how can I return the ref.key() back to the controller?
Modifying the example from the API guide:
var list = $firebaseArray(ref);
var addItem = function(itemDataObject) {
list.$add(itemDataObject).then(function(ref) {
var id = ref.key();
console.log("added record with id " + id);
list.$indexFor(id); // returns location in the array
});
};
How can I get that id variable to be returned when the addItem function is called? Even if I declare a variable outside the list.$add function and set the variable within the function, I get an undefined result.
One way would be to fall back to using Firebase's regular JavaScript SDK.
var list = $firebaseArray(ref);
var addItem = function(itemDataObject) {
var newItemRef = ref.push(itemDataObject);
var id = newItemRef.key();
console.log("added (or still adding) record with id " + id);
return id;
};
But if you need the key() of the new ref for anything more than displaying it, you'll need to wait until it's available.
In that case, the easiest approach is to return the promise:
var list = $firebaseArray(ref);
var addItem = function(itemDataObject) {
return list.$add(itemDataObject);
};
What happens next, depends on the calling code and what you want it to do.
Since you want to return the result of an asynchronous operation, you may benefit from reading my answer here and the links in it: Asynchronous access to an array in Firebase
One possible issue seems like having variable declaration of id even though that variable is declared globally.
For example:
var id;
function setIDVal1(){
var id=10;
}
function setIDVal2(){
id=101;
}
function getIDVal(){
alert(id);
}
Check this fiddle for the local variable issue & check this fiddle for an example to get the ID.

Updating Chrome storage object key value

I'm creating a Google Chrome extension and I'm saving information using the chrome.storage.sync.set function. According to the API you can create an object and save the information between accounts. While I am not having any trouble creating this object, I am having trouble updating a specific key and syncing the value, without making an entirely separate object for each change.
For example my object looks something like this when logged to the console:
{
profile: {
preferences: {
username: 'my username'
}
}
}
I'd like to simply update the value 'username'.
I've tried doing something like this (I have access to the object through the chrome.storage.sync.set function callback):
_ext.profile.preferences.username = 'my new username';
This does update the object, but does not save and store it.
I have also tried this method:
_ext.profile.preferences.username = 'my new username 2'; /* update the key value */
chrome.storage.sync.set(_ext.profile) /* save the entire object to memory */
This method has not worked either.
What do you think is the problem here? Is it the way in which I'm trying to save the object or is there a better method to having a settings based approach?
If you are calling "get" right away, before the "set" has completed, that could be the problem. Your example does not show a callback being passed to handle completion of the "set".
I stumbled across your post while looking to solve the same issue. I ended up using a similar approach as React Redux state management. Instead of trying to manipulate the stored data, I make a copy then replace it.
var data = {};
chrome.storage.sync.get(function(result){
data = result.storedData;
data.profile.preferences.username = 'my new username';
});
chrome.storage.sync.set({'storedData': data});

Categories