0

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.

My console.log

Giga Meta
  • 299
  • 2
  • 16
  • 1
    print state inside render – vinayak shahdeo Feb 11 '20 at 18:45
  • 1
    `setState` isn't synchronous, so `this.state` won't be updated immediately after calling `setState`. – SimpleJ Feb 11 '20 at 18:47
  • @SimpleJ Oh, do I need to use ```await``` then? – Giga Meta Feb 11 '20 at 18:48
  • 1
    @GigaMeta `await` won't work, `setState` does not return a promise, you can use the callback `this.setState({ id: this.state.id + 1 }, () => console.log(this.state))` – Taki Feb 11 '20 at 18:51
  • i assume in `this.loadData` you get data from an api. then you probably have to set the state only after you get the data. not only the data state, but also the id. get the data of the new id, then setState of the new id and the received data – Yosef Tukachinsky Feb 11 '20 at 18:53
  • 1
    This issue is also explained in the React docs for setState: https://reactjs.org/docs/react-component.html#setstate – Ed Lucas Feb 11 '20 at 19:00

1 Answers1

1

setState is asynchronous, refer https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0.

setState enables you to make a callback function after you set the state so you can get the real state. In your case

this.setState({id: value}, () => console.log(this.state.id));
PK07
  • 61
  • 3