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()});
});
}
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:
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
.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.child('clients')
from your code, since there is no clients
node under each child.