Zena Mesfin
Zena Mesfin

Reputation: 421

How can I reuse a function in react/redux app?

I have a link that saves the page.

    <Link
      onClick={this.savePDF}
      button="secondary" >
      Save as PDF
    </Link>

I have a save function that is being reused

save = (page) => () => {
  this.props.toggleSaving();
  this.props.savePage(page);
  this.props.toggleSaving();
};

 savePDF = (page) => {
  this.props.toggleSaving();
  this.props.savePage(page);
  this.props.toggleSaving();
  window.open(`${window.location.pathname}/print`, '_blank');
 };

This works for me but when i try to do this.

 savePDF = (page) => {
  this.save(page);
  window.open(`${window.location.pathname}/print`, '_blank');
};

It doesn't trigger this.save() although it opens the print page.

How can i organize this to make code repeat less.

Upvotes: 0

Views: 35

Answers (1)

Prakash Sharma
Prakash Sharma

Reputation: 16472

The save function is returning a new function when you call it like

this.save(page);

I dont see any need of returning a new function here. You can simply define the function like this and that will work

save = (page) => {
  this.props.toggleSaving();
  this.props.savePage(page);
  this.props.toggleSaving();
};
// And then calling it like this will work
this.save(page);

Upvotes: 2

Related Questions