I'm trying to add pagination to my react application. The problem is that my this.state.id
is not incrementing correctly. When I'm pressing my second button with id="2"
, the state is incrementing late and because of this, it is loading the old this.state.id
data. I don't know what the problem is
My logic:
State is starting with 1, because that is the first page
this.state = {id: 1}
handleClick = (e) => {
let value = e.target.id
let nextValue = e.target.value
if (nextValue === "Next") {
this.setState({ id: this.state.id + 1 })
}
else {
this.setState({ id: value })
}
console.log("This is value " + value)
console.log(this.state.id)
this.loadData(this.state.id)
}
My pagination buttons:
<div className="row">
<div className="col-sm-12">
<ul className="pagination justify-content-end">
<li className="page-item"><button id="1" className="page-link" onClick={this.handleClick}>1</button></li>
<li className="page-item"><button id="2" className="page-link" onClick={this.handleClick}>2</button></li>
<li className="page-item"><button id="3" className="page-link" onClick={this.handleClick}>3</button></li>
<li className="page-item"><button value="Next" className="page-link" onClick={this.handleClick}>Next</button></li>
</ul>
</div>
</div>
An example of what is happening:
When I press on the second button with id 2, it prints This is value 2
, but this.state.id
is still 1
. When I press on button 3, it prints This is value 3
, but this.state.id
is still 2
. This is causing my problem and it is fetching the wrong data for the page.