State is always one click late
if you want to access to revalue right after setting it you have to use useEffect with revalue as a parameter , it would be like this
useEffect(()=>{
console.log(revalue);
},[revalue])
now every time revalue change you will have current result
Hey so you have a clousure issue there
In JavaScript, closures are created every time a function is created, at function creation time.
At the time the .then()
function is created, revalue
has the value of the last render, That's why even after updating the state with setRevalue
(and thus triggering a rerender), you get the "old value" (the one corresponding to the render in which the .then
function was created).
I don't know exactly your use case, but seems like you can achieve whatever you are trying to achieve by doing:
const revalue = response.data.rates[0].mid
setRevalue(revalue)
console.log(revalue);