5
votes
export const USER_KEY = "isLoggedIn";

export const phoneVerified = () => AsyncStorage.setItem(USER_KEY, 1);
export const userInfoVerified = () => AsyncStorage.setItem(USER_KEY, 2);

I have used the above functions to store the value and the below one to get the value.

export const isSignedIn = () => {
  return new Promise((resolve, reject) => {
    AsyncStorage.getItem(USER_KEY)
      .then(res => {
          console.log("from isSignedIn : "+res); //res is showing null.
        if (res !== null) {
          resolve(res);
        } else {
          resolve(0);
        }
      })
      .catch(err => reject(err));
  });
};

Why this always returns null? I was trying async/await but still getting null. I think somehow the data is not storing.

3

3 Answers

1
votes

As answered by @Vishu Bhardwaj AsyncStorage accepts only string. So you can use JSON.stringify() and JSON.parse() in such cases.

0
votes

I was stuck with this stupid problem for almost one week, no other way that is suggested in all communities worked for me, but then I found something that is built of react-native which its setState() callback function: https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296. so the only way that I guarantee that it's the only secure way so far is this that u use the setState() function in your promise and everything that you need to run, put them on a function and call it for the setState() callback function , this is only way you can make sure yourself that you neither get null nor never calling the function . Here I'm going to provide an example of it which this.tokeToServer() is my function which it's used as a callback function.

try {
      AsyncStorage.getItem('firebase_token',(err,item) => {
        if (item) {
          this.setState({
            firebase_token: item,
          }),this.tokenToServer();
        }
      });
      } catch (error) {
      console.log("Error retrieving data" + error);
    }