I am trying to load all events that belong to a certain group when the user clicks that group but when the app starts and you click on the group initially nothing changes until you click the group again.
toggleGroup = (name, index, id) => {
this.setState({
group: name,
index: index,
id: id
})
this.setEvents(id);
}
setEvents(id){
let tempIdHold = [];
if(id != null){
const groupRef = fire.database().ref('groups').child(id).child('events');
groupRef.on('value', snapshot =>{
if(snapshot.val()){
snapshot.forEach(snap => {
tempIdHold.push(snap.key);
})
this.setState({hasEvents: true});
}else{
this.setState({hasEvents: false});
}
});
const eventsRef = fire.database().ref('events');
const tempEventHold = [];
tempIdHold.forEach(event => {
eventsRef.child(event).once('value', snapshot => {
console.log('eventsRef: ' + snapshot.key)
let newEvent = {
name:snapshot.val().name,
description:snapshot.val().description,
groupid:this.props.group,
id: eventsRef.push().key
};
tempEventHold.push(newEvent);
this.setState({
events: tempEventHold
});
});
});
}
}
Here are the functions I run when toggling the groups. It seems to be that the events array in the state isn't getting populated on the first click. I'm guessing that is because firebase and or setState are async. How do I make sure my render runs after the events array has been populated?