I want to receive success if data is pushed correctly to firebase or catch an error if rejected. I tried such a code:
db.push().set(todo).then(snap => {
console.log(snap);
});
but SNAP, callback, IS UNDEFINED . How do I need to use promises here?
A promise represents an operation and the future value it may return. It also lets you propagate errors similar to try/catch in synchronous code. You can read about promises in the Firebase SDK on The Firebase Blog, and promises in general on MDN.
Once the push method has created a new child, it returns a DatabaseReference object initialized with the path to that child. Calling the getKey() method on this reference will return the auto-generated key which may then be used to store a corresponding value.
Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.
Most of Firebase's APIs are asynchronous. This might be confusing at first: you're making a call, for example to fetch some data from Firestore, but you don't get a result back.
The .then does not return a snapshot of the data -- you will need to do a "once" snapshot of the data within the callback
db.push().set(values).then(() => {
console.log('Successfully set');
db.once('value').then((snap) => {
console.log(snap);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With