I am trying to remove/delete items from my Firebase Database onPress of a button. The following is my code for the method I'm using to attempt to remove the item.
let itemsRef = db.ref('/items');
handleRemove = (item) => {
itemsRef.remove({
name: item
});
}
My method for remove is the same implementation of the push method that adds items to the database.
I get an error stating that - "Error: Reference.remove failed: first argument must be a valid function"
See image of error screen
The remove method doesnt take an object as a parameter. You should only do this:
itemsRef.remove();
From the docs:
remove
remove(onComplete?: function): Promise
Removes the data at this Database location.
Any data at child locations will also be deleted.
The effect of the remove will be visible immediately and the corresponding event 'value' will be triggered. Synchronization of the remove to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the onComplete callback will be called asynchronously after synchronization has finished
Related
I saw on the Firestore documentation for realtime listener that we can view changes between snapshots and see whether each document is added, removed or modified.
I am wondering if it is possible to see the type of changes if I am only attaching onSnapshot to a single document?
I tried to run the docChanges() method on the single doc listener:
db.collection("matching").doc("user1").onSnapshot(async doc => {
doc.docChanges().forEach(function(change) {
if (change.type === "added") {
console.log("added: " + change.doc.data());
}
})
})
But it produced an error of :
Uncaught (in promise) TypeError: doc.docChanges is not a function
I think I simply cannot run docChanges() on a single doc listener. In that case, how to view changes for a single firestore doc realtime listener then?
No, the API will not indicate to you what data or fields changes between snapshots. You just get a callback every time something changed anywhere in the document. You have to compare the previous and current snapshot to figure that out for yourself.
This docChanges() method is applicable on listeners being run on the collection rather than documents, so if you want to check changes between the snapshot put the docChanges() after the collection reference.
I have a firebase realtime database trigger on a create node. my need is to update a property based on some condition in the create trigger for the same object. The way i am doing currently is below:
exports.on_order_received_validate_doodle_cash_order = functions.database.ref("/orders/{id}")
.onCreate((change, context) => {
console.log("start of on_order_received_deduct_doodle_cash")
const orderId = context.params.id
const order = change.val();
var db = admin.database();
const orderRef = db.ref('orders/')
return orderRef.child(orderId).update({"_verifiedOrder": true})
})
As you can see i am getting order id from context and then querying object again and updating it. My question is do i need to do this circus or can i just update it without querying again?
Generally it looks good. Just some small feedback to make you feel more confident about being on the right track.
Call the parameter snapshot instead of change because the parameter name change only make sense for the onUpdate event trigger.
You do not need to log that you're entering the function. Because entering and leaving the function is automatically logged by Firebase also.
You can remove the order variable that is unused.
You are actually not "querying" the object again. Making a reference to a node in the database doesn't make any network call itself. Not until you subscribe to receiving data. So doing orderRef.child(orderId) is not a query, it's just a database reference.
You can use the snapshot's own reference attribute to shorten your code a bit... effectively throwing away almost all code :-)
So your code code look like this instead. It is doing the exact same thing, just shorter. It was also correct from the beginning.
exports.on_order_received_validate_doodle_cash_order = functions
.database
.ref("/orders/{id}")
.onCreate((snapshot) => {
return snapshot.ref.child("_verifiedOrder").set(true);
});
But as mentioned in my comment above, you are effectively just setting a flag that is confirming that data was saved (or rather: confirming that the function was triggered). You might want to add some logic in there to check whether the order can be placed or not and then set the verified flag to true or false depending on that. Because with the logic of the implementation, all orders will have the value _verifiedOrder set to true, which is a waste of storage in your database.
I'm creating the user Follows / Unfollows portion of my app and I'm coming up with several issues. The latest deals with following a fellow user and saving some reference info under a "follows" node. I'm looking at my Firebase console while doing this in my simulator and noticed the information appears correctly in green and 1 second later changes to red in order to delete. Here is how I'm saving things...
Future<Null> follow() async {
await fb
.child('users/${currentUser}/Follows/${friendsUID}')
.update({"name": userName, "photo": userImage});
}
I'm running the following code before my Widget build in order to determine if the user is being followed and which buttons should build accordingly....
void _friends() {
fb.child("users/${userid}/Follows/${id}").onValue.listen((Event event) {
setState(() {
// this will return true or false which is what you want based on your code :)
friends = event.snapshot.value == null;
});
});
}
And occasionally I'm receiving the following error message, I'm not sure if its related to saving the Firebase though...
setState() called after dispose(): FriendsVideoPageState#51581(lifecycle state: defunct, not mounted)
This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
I'm following along the with the basic AngularFire2 docs, and the general format seems to be:
const items = af.database.list('/items');
// to get a key, check the Example app below
items.update('key-of-some-data', { size: newSize });
My confusion is that in the source code, it seems as though calling database.list() grabs all the data at the listed url (line 114 here)
Can anyone help clarify how that works? If it does indeed grab all the data, is there a better way of getting a reference without doing that? Or should I just reference each particular URL individually?
Thanks!
When you create an AngularFire2 list, it holds an internal Firebase ref - accessible via the list's public $ref property.
The list is an Observable - which serves as the interface for reading from the database - and includes some additional methods for writing to the database: push, update and remove.
In the code in your question, you are only calling the update method and are not subscribing to the observable, so no data is loaded from the database into memory:
const items = af.database.list('/items');
// to get a key, check the Example app below
items.update('key-of-some-data', { size: newSize });
It's only when a subscription to the observable is made that listeners for value and the child_... events are added to the ref and the list builds and maintains an internal array that's emitted via the observable. So if you are only calling the methods that write to the database, it won't be loading any data.
The AngularFire2 object is implemented in a similar manner.
I am new to meteor and want to modify database document from the user interface,
I understand that we have to use update function but unable to use it as I want to edit the collection from UI on click command, please suggest how to go about it.
Arguments
selector Mongo Selector, Object ID, or String
Specifies which documents to modify
modifier Mongo Modifier
Specifies how to modify the documents
callback Function
**Optional**. If present, called with an error object as the first argument and, if no error, the number of affected documents as the second.
Please suggest how to use modifier.
Lets put this on an example, using an event handler.
Template.example.events({
'click #updateThis':function(e,t){
var newValue = t.$('.newValue').val(); // taking value from random input
Collection.update({_id:this._id},{$set:{value:newValue}},function(error,result){
if(error){
console.log(error.reason)
}else{
console.log("Nice update")
}
})
}
})
So first the Selector, like it says it should be the ID of the document to modify.
the modifier in this example is the $set more about field update operators here
and the callback is to make it asynchronous, with the 2 parameters i like to use error and result