Reputation: 11
I have a function that is used to setState in my App.js script. I have passed this as props to my FilteringTable.js component which calls this function when a table row is clicked. It always takes an extra click to change the state. How do I fix this problem? Please help
App.js
class App extends React.Component{
state={
data:[]
}
setStateData = rowData =>{
this.setState({
data:rowData
})
};
render(){
return (
<Router>
<div className='App'>
<Header data={this.state.data}/>
<Switch>
<Route path="/filtertable" render={(props)=> <FilteringTable{...props}setStateData={rowData => this.setStateData(rowData)}/>}/>
</Switch>
<Footer data={this.state.data}/>
</div>
</Router>
)
}
}
export default App
FilteringTable.js
export const FilteringTable = (props) => {
return (
<>
<div className="content">
<table className="list-table"
{...getTableProps()}
onClick={()=> {props.setStateData(selectedFlatRows);
console.log("Clicked",selectedFlatRows)}}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
{column.render('Header')}
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{page.map(row => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>
{cell.render('Cell')}</td>
})}
</tr>
)
})}
</tbody>
</table>
</div>
</>
)
}
The onClick function in the table component is where the function to setState is used. And it takes an extra click to change the state. Thank you in advance!!
Upvotes: 0
Views: 748
Reputation: 5036
Try moving this call to useEffect
:
useEffect(()=> {props.setStateData(selectedFlatRows)},[selectedFlatRows])
Upvotes: 1