0

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.

  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – SRIDHARAN Jun 26 '20 at 14:43
  • https://stackoverflow.com/a/54069332/5349104 refer this answer. This is already answered here. – SRIDHARAN Jun 26 '20 at 14:44

1 Answers1

0

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))
李嘉伟
  • 21
  • 2