0

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 Answers 2

0

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) {
      
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

0

Use JSON.parse for values getting from AsyncStorage

https://react-native-async-storage.github.io/async-storage/docs/usage/#reading-object-value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.