Search code examples
reactjsfirebasefirebase-realtime-databasefirebase-console

Trying to have a unique number ID in firebase, using reactjs


I can't seem to set the counter value to the ID of the last inserted query. It seems to be empty?

componentDidMount() {
//Last inserted query
let postRef = firebase.database().ref('clients').orderByKey().limitToLast(1); 
//Fetch the data from the query
postRef.on('value', snapshot => {

  this.setState({ counter: snapshot.child('clients').child('ID').val()});

});


}

enter image description here


Solution

  • This should do the trick:

    let postRef = firebase.database().ref('clients').orderByKey().limitToLast(1); 
    postRef.once('child_added', snapshot => {
      this.setState({ counter: snapshot.child('ID').val()});
    });
    

    Changes I made to your code:

    • This now uses once instead of on, because I assume you don't intend to get continuous updates. If you do want to receive updates as keys are added/removed, use on.
    • I listen for child_added since that fires for the correct child node. If you listen for value you'll need to loop over the snapshot (with snapshot.forEach() to get to the child node.
    • I removed the child('clients') from your code, since there is no clients node under each child.