Michael
Michael

Reputation: 1674

Why does only one of my functions in onClick execute?

I'm trying to call two methods when a tab on my navigation bar is clicked. I originally only had one method being called until I realized that I needed to call the second one to update my data. The problem is that when I try and call both methods, only one of them is executed and never both. I've had multiple functions in an onClick method before and they work fine but I'm a little confused why this way isn't working. Any help would be great, thanks!

app.js


export default Class App extends React.Component{
 constructor(props){
  this.state = {
   OpenJobsDB: [],
   PendingJobsDB: [],
   CompletedJobsDB: [],
   page: undefined,
  };

  this.setPage = this.setPage.bind(this);
  this.PullJobsTables = this.PullJobsTables.bind(this);
 }
}
    PullJobsTables() {
        console.log("pulling jobs from DB");

        socket.emit('selectFromJobsWhereOpenAwaitingETAsAssigned', function (result) {
            this.setState({ OpenJobsDB: result });
        }.bind(this));

        socket.emit('selectFromJobsWherePending', function (result) {
            this.setState({ PendingJobsDB: result });
        }.bind(this));

        socket.emit('selectFromJobsWhereCompleteDeleted', function (result) {
            this.setState({ CompletedJobsDB: result });
        }.bind(this));
    }

    setPage(e) {
        console.log("inside setpage");
        var naviBtns = document.getElementsByClassName('NavigationBarButtons');
        for (var i = 0; i < naviBtns.length; i++) {
            naviBtns[i].style.backgroundColor = '#333a56';
            naviBtns[i].style.bottomBorder = '0';
        }
        e.target.style.backgroundColor = '#e14658';
        e.target.style.bottomBorder = '3px solid #FFA279';

        const page = e.target.name;
        this.setState(() => ({ page }))
        this.OpenNavigationBar('close');
        this.setState({
            showReportsList: false,
            showTablesList: false,
            showTimeOff: false,
        });
    }
}

My onClick looks like this


<button onClick{() => {this.setPage.bind(this); this.PullJobsTables.bind(this);}}

In this example the only one that get's called is the PullJobsTables method and not the setPage method. This is the way I've done it in similar situations and it works fine. This is kind of confusing me as to why it's not calling both.

Upvotes: 0

Views: 62

Answers (1)

Drew Reese
Drew Reese

Reputation: 202751

Both those functions already had this bound to them in your constructor. You also need to pass the event to the callbacks that are expecting it.

<button
  onClick={event => {
    this.setPage(event);
    this.PullJobsTables();
  }}
>

Upvotes: 2

Related Questions