Abhirup Mukherjee
Abhirup Mukherjee

Reputation: 499

Store DateTime Value in AsyncStorage while the AppState Changes

I am trying to store DateTime Value when the state of App changes.For suppose the app is in Background and I want to store the value of DateTime in AsyncStorage and when the app is in active state I want to calculate the time difference. But the promise which i get as a return value is null. My RN Version is 56.0 can anyone help me out?

StoreDate = async () => {
        await AsyncStorage.setItem('date', new Date());
      };

      retrieveDate = async () => 
      {
        try{
        let value = await AsyncStorage.getItem('date');
        console.log("value",value);
        Alert.alert(value);
        return JSON.parse(value);

    }
          catch(error){
            Alert.alert(error);
          }
      };

     if (this.state.appState.match(/inactive/) && nextAppState === 'background') {
    let getDateTime = this.StoreDate().then((filter) => {
            console.log("filter",filter);
            console.log("getDateTime",getDateTime);
          });
    }

** Null promise returned when trying to retrieve the values using getItem **

enter image description here

Upvotes: 0

Views: 1646

Answers (1)

yangguang1029
yangguang1029

Reputation: 1823

you should store date as string, and change it to Date when retrieving,like

StoreDate = async () => {
    await AsyncStorage.setItem('date', new Date().getTime());
  };

retrieveDate = async () => {
    try{
        let value = await AsyncStorage.getItem('date');
        console.log("value",value);
        Alert.alert(value);
        return new Date(parseInt(value));
    }
    catch(error){
        Alert.alert(error);
    }
};

if (this.state.appState.match(/inactive/) && nextAppState === 'background') {
    let getDateTime = this.StoreDate().then(() => {
        this.retrieveDate().then(data => {
           console.log('retrieve data ' , data)
        })
      });
}

Upvotes: 1

Related Questions