Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sending updated value to API with useState

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading