Convert variable stored in AsyncStorage then state to Number


#1

How can I convert an AsyncStorage stored number (stored as a string) to a Number in react native (I am using Expo).

It works converting the string to a number like this:

myNum = Number('3'); // THIS WORKS

But this does not work:

myNum = Number(this.state.myStateNum); // This does not work, returns zero

myNum = Math.floor(this.state.myStateNum); // This does not work, returns zero

myNum = parseInt(this.state.myStateNum); // This does not work, returns NaN

If it helps this is how I set using async:

async function setItem(key, value) {
  try {
    await AsyncStorage.setItem(key, value);
    console.log(key, value);
    return value;
  } catch (error) {
  }
}

setVar = setItem('myStateNum', '3');

This is how I get using async:

async componentWillMount() {
  const myStateNumGet = await AsyncStorage.getItem('myStateNum');
  if (myStateNumGet) {
    this.setState({ myStateNum: myStateNumGet });
  } else {
    this.setState({ myStateNum: false });
  }
}

Any suggestions/help would be great.


#2

@groupofdots parseInt seems to work with getItem and setItem, see https://snack.expo.io/r1gNJ-jjZ


#3

Many thanks and sorry for the delay in replying I was in transit.

Is there a way to do:

 let num = parseInt(this.state.myStateNum);

‘Before’ render() ?