Reputation: 306
I have this scenario which inside a function I change the state, call to async method and then want to use the updated state. the problem is that the state did not change altho is run after async call:
function MyComponent(){
const [values, setValues] = useState<number[]>([]);
const updateValue = () => {
setValues(values.push(1));
myAsyncMethod().then(()=>{
console.log(values); //still empty array '[ ]' !
setValues(values.remove(1)); //no value to remove
});
};
return(
<OtherComponent values={values} updateValue={updateValue}/>
);
}
what is missing? I don't want to use 'useRef' since i want to re render when the value change. Is there a way so I can get the updated state after the async call?
Upvotes: 0
Views: 66
Reputation: 4748
From your code chunk:
const updateValue = () => {
setValue(2);
myAsyncMethod().then(()=>{
console.log(value); //still '1' !
});
};
setValue
is also asynchronous. So, that's why you are still getting the value as 1. According to your scenario, you will be getting the value to set. You can pass that rather than the state variable as:
const updateValue = newValue => {
setValue(newValue);
myAsyncMethod().then(()=>{
console.log(newValue);
});
};
Hope this will help you.
Upvotes: 1