React-native-firebase: Get Ref Key after push?

Created on 6 Jun 2017  路  10Comments  路  Source: invertase/react-native-firebase

Hey Guys,

First of all thanks for your work on this!

The firebase web documentation here: https://firebase.google.com/docs/database/web/read-and-write describes the ability to get a key from a newly pushed ref like this

  // Get a key for a new Post.
  var newPostKey = firebase.database().ref().child('posts').push().key;

This doesn't seem to work using this, as push() seems to return a promise. Also from what I can tell, the source code has a return type of void. Is there a way to do this?

Bug JavaScript Database

Most helpful comment

const postKey = firebase.database().ref().child('posts').push().key; works for me with "react-native-firebase": "^1.0.10",

All 10 comments

Figured it out. Need to handle the push as a promise callback.

Maybe it would be a good idea to start a reference doc on differences between this and the web library?

const postKey = firebase.database().ref().child('posts').push().key; works for me with "react-native-firebase": "^1.0.10",

Any of the maintainers know if something could have changed this behavior?

Push should definately be returning a new reference instance as per rhe web sdk only if push was called with no value, if it's called with a value then it should return a promise.

Source: https://github.com/invertase/react-native-firebase/blob/master/lib/modules/database/reference.js#L119

What version are you on @jsm because this has been here for quite some time :)

There should be no differences from the web sdk for database, if there is then it's something we've missed and will normally get fixed in the release following being notified of the discrepency. This is why our docs are generally slim, as the official firebase docs cover it.

@Salakar I'm on 1.11.0

Ah I see, yeah I'm calling it with a value which returns a promise on native, but returns the reference object on web.

Ah I see, so the web returns a reference that has a fake promise attached whereas we just return the promise. We'll look at sorting for v2.

In the meantime you can just do:

const ref = firebase.database().ref('posts').push();
const key = ref.key;

ref.set(value).then(...).catch(...)

Sweet, thanks!

v3 (not released yet) now supports thenable refs for push.

Thanks for flagging the issue :)

@Salakar it doesn't seem so, if I use await it returns null to me. Opened #893.

use this:

var TheUniqueKeyOfPush = firebase.database().ref().push().getKey();

and then:

Use the variable because it contains the unique key.

Was this page helpful?
0 / 5 - 0 ratings