0

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!!

1
  • You should edit your post and only add a minimal, reproducible example. If I strip your components down your code works as expected. Commented Jan 29, 2021 at 20:20

1 Answer 1

1

Try moving this call to useEffect:

 useEffect(()=> {props.setStateData(selectedFlatRows)},[selectedFlatRows]) 
Sign up to request clarification or add additional context in comments.

2 Comments

How would that work on click? Although to be honest the original question is not really clear.
From what I understood from the user's previous question selectedFlatRows is a state variable and it is updated on click, so it make sense the callback gets the previous version. I might be wrong though

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.