Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js - How to call a method after another method is fully executed

I have two simple functions. I am trying to call two functions in my "handleSearchClick" function when the button has been clicked.

I would like to run "this.props.getNewsDesc()" after "this.props.fetchNewsApiOrg(this.newsSourceName)" has been fully executed.

Here is the code:

handleSearchClick = () => {
    this.props.fetchNewsApiOrg(this.newsSourceName);
    
    this.props.getNewsDesc();
  }

Could you please tell me the proper way to call a function after another function is fully executed?

Thank you.

like image 852
Eunicorn Avatar asked Mar 07 '23 04:03

Eunicorn


1 Answers

You can pass the method as a parameter and call the function from within the fetchNewsApiOrg().

handleSearchClick = () => {
    this.props.fetchNewsApiOrg(this.newsSourceName, this.props.getNewsDesc);
 }
...
fetchNewsApiOrg(newsSourceName,getNewDesc){
...
getNewDesc();
}

In this method you will have to bind getNewDesc like, this.getNewDesc = this.getNewDesc.bind(this) in constructor.

Or you can go with promises.

handleSearchClick = () => {
    this.props.fetchNewsApiOrg(this.newsSourceName).then(()=>{
    this.props.getNewsDesc();
  })

Here the fetchNewsApiOrg should return a promise.

like image 162
Rohith Murali Avatar answered Mar 17 '23 04:03

Rohith Murali