Atomic Rooster Atomic Rooster - 3 months ago 13
React JSX Question

Sending row/cell data on click to the function - ReactJS

I am retrieving table data from componentWillMount and showing it as UI. I want to trigger a fuction when the row/cell is clicked and return that value back to another PHP so that i can query the backend using that retrieved cell value.

index = 0,1,2,3 ( I have 4 coulumns )

row = data for each index.

I am not sure why this.state.testTime is not sending the correct value to handleClick function. Does anyone have any inputs on this? Thanks.

_handleClick: function (event) {
this.setState({testTime: event.target.value});
console.log(event.target.value);
var data = {
testTime: this.state.testTime
}

console.log("clicked");
$.ajax({
type: "GET",
crossDomain: true,
url: "http://localhost:8080/TEST/capture.php",
data: data,
success: function(data){
alert(data);
},
error:function(data)
{
alert("Data sending failed");
}
});
},

return (
<tbody>
{tableData.map((row, index) => {
return (
<tr key={"row_" + index} >
{row.map((cell, index) => {
return (
<td key={"cell_" + index} onClick={this._handleClick} value={this.state.testTime} >{cell}</td>
);
})}
</tr>
);
})}
</tbody>
)

Answer

setState is an async function and it accepts a callback as the second argument that will be executed once setState is completed and the component is re-rendered. So you either need to use event.target.value directly for the data variable or put your code into the callback:

this.setState({testTime: event.target.value} ,() => {
   var data = {testTime: this.state.testTime}
   ...
   $.ajax...
});