Avinash
Avinash

Reputation: 426

how to setstate on button click event in a table

I have master-detail table in react. If I select (or click a button) on a row in the master table, I want to set a state variable with the id of the selected row, which will be used to render the details table for that ID. However, react does not allow me to use setState in the event function.

  constructor(props){
super(props);
this.state = {
  customer: {},
  customerRequests: [],
  interactions: [],
  order: [],
  error: '',
  selectedCustomerRequest: ''
}
this.onSelectCustomerRequest = this.onSelectCustomerRequest.bind(this);

}

The event function is

  onSelectCustomerRequest(id){
console.log(id)
// this.setState({selectedCustomerRequest: id});

}

The HTML is

          <tr key={item._id} onClick={this.onSelectCustomerRequest(item._id)}>
        <td><button onClick={this.onSelectCustomerRequest(item._id)} /></td>
        <td>{moment(item.orderDate).format('DD/MM/YYYY hh:mm')}</td>
        <td>{item.genericName}</td>
        <td>{item.quantity}</td>
        <td>{item.priority}</td>
        <td>{interaction.orderStatus}</td>
        <td>{moment(interaction.created).format('DD/MM/YYYY hh:mm')}</td>
        <td>{interaction.createdBy}</td>
      </tr>

if I enable the setState in onSelectCustomerRequest(id){} I get error. secondly I see that the onSelectCustomerRequest() gets executed for every row as I can see it console.log on my terminal.

I want to setState only when I click the button only.

I am sure I am doing a silly mistake somewhere, can you help? Please.

Upvotes: 1

Views: 644

Answers (1)

Alexei Crecotun
Alexei Crecotun

Reputation: 156

the problem here is that you call the function immediately by add parentheses () in the end of method.

To make it work, I would recommend create a closure within a method, so your case it would look like

onSelectCustomerRequest(id) {
  return () => {
    console.log(id)
  }
}

So you basically by calling onSelectCustomerRequest in onClick return a function, which you can fire late.

Upvotes: 2

Related Questions