'useState set value cannot update immediately
I want to change to the value of one useState item then set item to AsyncStorage, but I found that the value of useState is still kept previous value and then saved to AsyncStorage. Please help what can I do ? Many Thanks
below is my sample code:
const [myGetNo,setMyGetNo] = useState(0)
useEffect(()=>{
console.log('useEffect ',myGetNo)
},[myGetNo])
_storeData =async () => {
try {
setMyGetNo(2)
let myTicket ={myGetNo:myGetNo}
await AsyncStorage.setItem('myTicket',JSON.stringify(myTicket))
}
} catch (err) {
console.log('AsyncStorage SetItem Error: ',err)
}
};
As a result: the value of myGetNo is still initial value 0 , not 2 , saved in AsyncStorage.
Solution 1:[1]
The value of state myGetNo is only updated after rerendering. So in the try and catch blocks, the AsyncStorage is using the old myGetNo value.
To solve this, update the try block like this:
const newNo = myGetNo + 2
setMyGetNo(newNo)
let myTicket ={myGetNo: newNo}
await AsyncStorage.setItem('myTicket',JSON.stringify(myTicket))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ??? |
