Home > Software design >  Count value Sate not getting updating - React JS
Count value Sate not getting updating - React JS

Time:08-03

When load more is clicked, count value is not getting updated only on the second click it is getting updated.

Expectation is on load more button click value should be passed as 2, but now it is sending as 1.

what I'm doing wrong here. Please guide

Below is the sample code.

const [count, setCount] = useState(1);

fetchData() {
.....
}

loadMore() {
 ....
 fetchData()
}

Render HTML Method:

<button onClick={ () => {
setCount(count   1);
loadMore();
}}

CodePudding user response:

use this -

const handleOnClick = () => {
    setCount((count) => count   1);
    loadMore();
}}

<button onClick={handleOnClick}>Click me</button>

CodePudding user response:

You may check the answer here in this react documentation.

I’ve updated the state, but logging gives me the old value.

  • Related