0

I'm trying to update a usestate count in axios response, its not working correctly.

let [ validationCount , setValidationCount ] = useState(0);


function getValidationResponse(validationUrl:string, validationKey:string)
    {
           axios.get("https://test.com/health")
                .then(res => {
                    setValidationCount(validationCount+1);
                }).catch(err => {
                
            });
            
        return "";
    }

above function gets called twice but validation count is always 1.

is there something I'm missing?

2 Answers2

1

Depending on how getValidationResponse is used, I suspect there might be a issue with closure that captures validationCount as 0 resulting the updated value to be 1 always.

Try using functional updates which will update the value of validationCount based on the previous value.

setValidationCount(prevCount => prevCount + 1);
subashMahapatra
  • 6,339
  • 1
  • 20
  • 26
0

It's a closure problem, you can see it in action here, basically, if you click on it slowly, it works fine, if you click on it multiple times before the previous update is concluded, you create functions where validationCount still hasn't updated. It's always good to remember that setState is an async function.

Arthur Bruel
  • 678
  • 3
  • 12
  • For more info about this, you can refer to [mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures). – Arthur Bruel Jul 09 '20 at 20:49