0

I use React Native Firebase for working with Firebase. In redux action I have:

export const startAction = (item) => {


    return (dispatch) => {

        firebase.database().ref(`/users/${firebase.auth().currentUser.uid}/some/`)
            .push(item).then((snapshot) => {
                console.log('Added to firebase', snapshot,  snapshot.key);

            }).catch((err) => { console.log('errooooor', err) });
    }


}

In then() I should get snapshot of inserted data, but I get null. How is that possible?

Error text: Cannot read property 'key' of null

John Smith
  • 1,204
  • 3
  • 22
  • 42

1 Answers1

2

According to the Firebase docs (https://rnfirebase.io/docs/v5.x.x/database/reference/Reference#push), Reference.push() does not return a promise. It returns a reference.

If you would like to know when the write to the server is complete, you can pass a callback function as a second parameter to the .push() function.

export const startAction = (item) => {
    return (dispatch) => {
        firebase.database().ref(`/users/${firebase.auth().currentUser.uid}/some/`)
            .push(item, error => {
                if (!error)
                    console.log("Item added to firebase");
                else
                    console.warn("There was an error writing to the database, error);
            })
    }
}

EDIT: Based on Salakar's comments here and on this Github issue:

without the await is also correct as creating a new reference + id path via push() is synchronous/client sided

You should be able to do the following:

const ref = firebase.database()
                .ref(`/users/${firebase.auth().currentUser.uid}/some/`)
                .push(item)
// Now do something with `ref.key`
Luis Rizo
  • 2,009
  • 4
  • 15
  • 34
  • 2
    This is a known bug, we'll get it fixed for v5.1.0 - thanks! – Salakar Oct 07 '18 at 03:18
  • Just to make sure I understand, you will make `.push()` return a promise. Is that correct? – Luis Rizo Oct 07 '18 at 03:20
  • It'll be made to match the Firebase Web SDK, see: https://github.com/invertase/react-native-firebase/issues/893 – Salakar Oct 07 '18 at 03:30
  • I need to know not just when the write to the server is completed, but I need to know ID of inserted data set, so that I could save it to Redux store. Work is stopped, what to do? Delete RNFB and use original library? – John Smith Oct 07 '18 at 13:00
  • Is there any way to know inserted data ID right after firebase query? – John Smith Oct 07 '18 at 13:49
  • Salakar, what is your thanks for? What is temp solution? How to get ID of pushed item and do something after that? – John Smith Oct 07 '18 at 19:49
  • 1
    I updated my answer with a possible solution. Check it out @JohnSmith – Luis Rizo Oct 08 '18 at 19:04