Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return promise in firebase set()

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?

like image 427
rick1 Avatar asked Feb 12 '18 20:02

rick1


People also ask

What is promise in Firebase?

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.

What is getKey () in Firebase?

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.

How do I get data from Firebase?

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.

Are Firebase functions async?

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.


1 Answers

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);
  });
});
like image 94
Katherine R Avatar answered Sep 19 '22 15:09

Katherine R