Counter with Async Storage in React Native

601 views Asked by At

I am new to React Native. I want to make a counter using Async storage in React Native Expo. Async storage works with string value but I need to use integer value and can't find an example to create it.

I would appreciate it if you suggest with SQLite or if there is a different storage area.


  storeData = async (counter) => {
    try {
      await AsyncStorage.setItem('', counter)
    } catch (e) {
      
    }
  }
  getData = async () => {
    try {
      const value = await AsyncStorage.getItem('counter')
      if(counter !== null) {

      }
    } catch(e) {
      
    }
  }

  render() {
      return(
        <SafeAreaView style={styles.container}>
          <ImageBackground  style={styles.image}>
              <View style={{marginBottom: 250}}>
                    <Text style={styles.counter}>{counter}</Text>
              </View>
              <TouchableOpacity 
                style={styles.floatingButton1}
                onPress={this.onAddCounter}>
                <Text style={{fontSize:13, color:"white", fontWeight:"600"}}>Tap to Counter</Text>
              </TouchableOpacity>
             <TouchableOpacity 
              style={styles.resetButton1}
              onPress={this.onReset1}>
                <Icon name="undo" size={20} color="#900"/>
             </TouchableOpacity>
          </ImageBackground>
        </SafeAreaView>
      );
    }

  }

2

There are 2 answers

0
Auticcat On BEST ANSWER

You can convert the integer to a string when you store the value:

number.toString()

And convert it to integer when you retrieve the value

parseInt(string)

Basically it will become

storeData = async (counter) => {
    try {
      await AsyncStorage.setItem('counter', counter.toString())
    } catch (e) {
      
    }
  }
  getData = async () => {
    try {
      const value = await AsyncStorage.getItem('counter')
      if(counter !== null) {
          value = parseInt(value)
      }
    } catch(e) {
      
    }
  }
0
Vasyl Nahuliak On