user3622460
user3622460

Reputation: 1251

Can I set the state and call a function on one button click?

I have a button and when I click on it I'm using onClick to set the state and call a function. When I pair the two actions together, it seems to only set the state.

If I remove the sitting the state function, the handleClick function works. Can you have multiple function calls in an onClick function? I searched around here and found a post stating that you could, not sure if my code is incorrect.

class OverviewRender extends Component {
    constructor(props) {
         super(props);
         this.state = { 
             Selected: 'MainMenu',
             name: ''
         }
       }

    componentDidUpdate() {
        console.log("OverviewRENDER update name: " + this.state.name);
    }

    handleClick(e) {
        e.preventDefault();
        let helpFileName = this.state.name;
        helpFileName = helpFileName.toLowerCase().trim();
        //Cap the first letter in the name and add the rest of the name 
        helpFileName = helpFileName.charAt(0).toUpperCase() + helpFileName.substr(1);
        this.props.handleHelpChange(helpFileName);
        console.log("pressed " + helpFileName);
    }

The button calling onClick...

  <RaisedButton 
     label="Load Default Values"
     name="One"
     value={this.state.name}
     onClick={() => {this.handleClick.bind(this), this.setState({ name: 'One' })}} 
     style={buttonStyle}
   />

Upvotes: 0

Views: 1094

Answers (2)

Andrew Li
Andrew Li

Reputation: 57964

That's because you're not executing the function. Function#bind returns a new function with the specified this and other supplied arguments bound. You have to execute it. Anyways, since you're using an arrow function, there's no need to bind anyway. Lastly, just set state inside handleClick, and pass in any variables you need to:

onClick={(e) => this.handleClick(e, 'One')}

And handleClick:

handleClick(e, num) {
  this.setState({
    name: num
  }, () => {
    e.preventDefault();
    let helpFileName = this.state.name; //or num
    helpFileName = helpFileName.toLowerCase().trim();
    //Cap the first letter in the name and add the rest of the name 
    helpFileName = helpFileName.charAt(0).toUpperCase() + helpFileName.substr(1);
    this.props.handleHelpChange(helpFileName);
    console.log("pressed " + helpFileName);
  });
}

Also note that I'm setting state first, then using a callback because setState is asynchronous. You have to wait until it is set to access it and get the right value.

Upvotes: 4

Mark Rabey
Mark Rabey

Reputation: 1415

You could either have the handleClick set the state, as mentioned in the previous answer, or your onClick could call handleClick in the callback:

<RaisedButton 
 label="Load Default Values"
 name="One"
 value={this.state.name}
 onClick={() => { this.setState({ name: 'One' }, this.handleClick.bind(this) }} 
 style={buttonStyle}
/>

Upvotes: 1

Related Questions