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
CodePudding user response:
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>
CodePudding user response:
I think that's because your count state changed but component is not rerendered yet
you can handle it in this way :
onClick={() => {
setCount((prev) => {
fetchCalculatedService(
Date,
Id,
filter,
Time,
prev 1
);
return prev 1
});
}}