I have an API that gets count. whenever user clicks on IconButton I must send the count to my server, but it always sends previous value. like if count is 1 it sends 0.
const { fetchCalculatedService, response } = useCalcService();
const [count, setCount] = React.useState(0);
<IconButton
color="success"
disabled={!selectInsurance}
onClick={() => {
setCount((prev) => prev + 1);
fetchCalculatedService(
Date,
Id,
filter,
Time,
count
);
}}
>
<ArrowUpward />
</IconButton>
I logged my response and my count as well. the count is the lastest count and everthing is ok but API response shows 0 in count.
I also looked at server logs. API receives 0
shouldn’t it get latest value of count whenever I call it? because value updated before fetchCalculatedService invoke
>Solution :
The solution to this is to perform the fetch inside the prev callback of your state update function. Since react states are being updated async, it count is not guaranteed to update immediately after setCount.
By fetching inside that callback you can manually raise your count variable.
<IconButton
color="success"
disabled={!selectInsurance}
onClick={() => {
setCount((prev) => {
fetchCalculatedService(Date, Id, filter, Time, prev + 1);
return prev + 1;
});
}}
>
<ArrowUpward />
</IconButton>