Alexander McComb
Alexander McComb

Reputation: 89

Reading data after writing to it in Firebase

I am trying to navigate to a specific ID after creating an item in my realtime database.

The documentation offers a solution but it is not working as shown.

After using the push().set() method on my db ref I tried creating a callback function that would get the specific ID created using the push.().set() method and then navigate with that ID.

db.ref.push().set({
    ...
}).then(function(){
    router.navigate(ref/ + db.ref.key /)
})

After creating a new object at that ref point I want to use the ID created by firebase to navigate to a specific route using that ID.

Upvotes: 1

Views: 507

Answers (2)

Joelgullander
Joelgullander

Reputation: 1684

set

set(value, onComplete) => returns firebase.Promise containing void

So you are absolutely correct about that you should be able to see the operation as resolved with a callback however the promise will not give you any key back.

You should however be able to chain this event:

db.ref.push().set({
    ...
}).getKey().then(data => console.log(data))

Upvotes: 1

Prisoner
Prisoner

Reputation: 50701

The issue is that db.ref.push() returns a new Reference object with the unique id to it. You're not getting the value of that ID. You can refactor things so it would be something like:

let newref = db.ref.push();
newref.set({
  ...
})
.then( () => {
  // You can use "newref" here
  // The last part of the full reference path is in "key"
  let id = newref.key;

  // Do something with the id as part of your route
});

Upvotes: 2

Related Questions