2

i am using ionic react with below code. Where i am fetching data from firebase and then trying to set it to a state variable. however it does not seems to set and the code is fairly starightforward. how do i make sure it is set before i can do next operation on this value?

const Tab5: React.FC = () => {
   
    const [coins, setCoins] = useState(0)

useIonViewDidEnter(async() => {
       console.log('ionViewDidEnter event fired');

       console.log("user data from firebase is", usrVal)
       if(usrVal === null || usrVal.coins === undefined){
          setCoins(0)
          setDiviCoins(0)
       }else{
          console.log("we are here to set conversion")
          setCoins(+usrVal.coins)
          console.log("coins after set is::" + usrVal.coins, coins)
       }
    });
```

logs print like below

```
[log] - user data from firebase is {"coins":553,"theme":{"dark":"rgb(175,8,8)","light":"rgb(255, 255, 255)"}}
⚡️  [log] - we are here to set conversion
⚡️  [log] - coins after set is::553 0
```

i have no idea why setCoins is not working?
Moblize IT
  • 1,140
  • 2
  • 18
  • 44
  • 2
    Unless ionic modifies how `setState` works, then `await setCoins(+usrVal.coins)` doesn't work the way you think it does. Setting state doesn't return a promise and therefor can't be awaited, so your `console.log` will occur before the value has changed. – DBS Nov 02 '21 at 17:13
  • 2
    `setState` actions are asynchronous but doesn't return a promise, so using await is meaningless for `setCoins`. – Hassan Imam Nov 02 '21 at 17:16
  • sure but how do i do the operations that relies on the value of coins? – Moblize IT Nov 02 '21 at 17:18

0 Answers0