Search code examples
jsonreact-nativereact-native-iosasyncstorage

AsyncStorage Converting Promice to JSON Formate


The Code Is Giving Two Different Outputs At Different Places After A Lot Of Try I could not figure it out. Please Help Me With This I Am New To React Native. console.log(files) This Function Gives One Output and console.warn( jsonValue != null ? JSON.parse(jsonValue) : null); gives another output

   storeData = async () => {
    try {
      const jsonValue = JSON.stringify(
              {
                  "Belgin":"Test Check"
              }
      )
      await AsyncStorage.setItem('BelginKey', jsonValue)
    } catch (e) {
      console.log(e)
    }
  }

  getData = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem('BelginKey')
      console.warn( jsonValue != null ? JSON.parse(jsonValue) : null); // Output as {"belgin":"Text Test"}
      
    } catch(e) {
      console.log(e)
    }
  }

  change_and_display=()=>{
      const files = this.getData()
      console.log(files) // Output as {"_40": 0, "_55": null, "_65": 0, "_72": null}
  }
    

render(){
    return(
        <SafeAreaView style={styles.container} >
            <TouchableOpacity onPress={this.storeData} style={{height:"10%",width:"100%",backgroundColor:"#000"}}>
                <Text style={{color:"#FFF"}}>Click This To Add Value</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={this.change_and_display} style={{height:"10%",width:"100%",backgroundColor:"#a1a1a1"}}>
                <Text style={{color:"#FFF"}}>Click This To Get Value</Text>
            </TouchableOpacity>
            <Text></Text>
            
        </SafeAreaView>
    )
}

}


Solution

  • You forgot to return your value in your getData() it s why it doesn't work.

    Also don't forget that an async function return a Promise, so to get the value the value of getData() either use async/await or .then()

    And then when you use OnPress(), don't forget to always put an arrow function inside so it only render when you press.

    example : onPress={() => this.storeData}