Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event like componentDidUpdate, but fired only once

I have some components that should do some work as soon as their data has arrived and rendered for the first time, but not for future rerenderings. For example: Comments are loaded and rendered, now 1. load social media libraries and 2. load some Google Analytics.

Right now I'm doing it like that:

componentDidUpdate: function (prevProps, prevState) {
    if (this.hasAlreadyUpdatedOnce) {
        // ... do some stuff...
    } else {
        // ... do some stuff that should happen only once...
        // 1. load social media libraries
        // 2. load some Google Analytics
        this.hasAlreadyUpdatedOnce = true;
    }
}

But I'm asking myself if there's a more elegant way than setting a property like that.

like image 960
kraftwer1 Avatar asked Jan 08 '23 22:01

kraftwer1


1 Answers

Assuming you're responding to a state change, you should pass a callback as the second argument to setState.

componentDidMount: function(){
  ajaxyThing(function(data){
    this.setState({data: data}, function(){
      // this.state is updated, the component has rerendered 
      // and the dom is current
    });
  }.bind(this));
}
like image 149
Brigand Avatar answered Jan 11 '23 14:01

Brigand