1

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?

Ben Cavenagh
  • 608
  • 1
  • 6
  • 22

1 Answers1

0

Probably Because of this

 this.setState({
        group: name,
        index: index,
        id: id
    })
    this.setEvents(id);

setState takes time to execute, meaning when you call setEvents your changes to setState won't have been completed.

There are two ways to do it, The first one would be to use async event and the other one would be to pass this.setEvents(id) in this.setState callback

this.setState({
   group: name,
    index: index,
    id: id
}, () => this.setEvents(id));

Update: On again going through your code, you aren't using this.state.xyz anywhere in your code, rather you are passing ID so it shouldn't affect your app.

You probably might need to share so more code/or create a working demo for us to identify

Also, I haven't used firebase before but operations from firebase takes some time to complete, better you should use promises in your code

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210