maxpill
maxpill

Reputation: 1331

React Native - Add a listener to Async Storage value change

Hello I set the value of AsyncStorage.getItem('authStatus') on LoginPage but the problem is that the Navigator class doesnt respond to value change of AsyncStorage. How to add listener to AsyncStorage.getItem('authStatus')?

    export default class Navigator extends React.Component {
      constructor(props) {
        super(props);
        this.state = { authStatus: ''}
      }
    
    
      async componentDidMount() {
        var authStatus = await AsyncStorage.getItem('authStatus');
       **DOESN'T WORK ->** authStatus.addListener(authStatus => {
          this.setState(this.state.authStatus = authStatus)
        });
        console.log("authStatus =")
        console.log(this.state.authStatus)
        SplashScreen.hide()
      }

 render() {
    return (
      (this.state.authStatus == 'authenticated')
        ?
        this.Home()
        :
        this.AuthStackScreen()
    );
  }

Upvotes: 4

Views: 5955

Answers (2)

Muni Kumar Gundu
Muni Kumar Gundu

Reputation: 532

Async Storage is asynchronous, unencrypted, persistent, key-value storage solution for your React Native application. It does not provide any events. It returns a promise.

Refer: https://react-native-community.github.io/async-storage/docs/usage

In your code "authStatus" may or may not contains a value.

try {
    const authStatus = await AsyncStorage.getItem('')
    if(value !== null) {
      // value previously stored
    this.setState({authStatus})
}

Upvotes: 1

yesIamFaded
yesIamFaded

Reputation: 2068

I dont know if you are using AsyncStorage in the right way... try something like this:

You can store and retrieve your data like this with AsyncStorage:

  const storeData = async (key, value) => {
    try {
      await AsyncStorage.setItem(key, value); 
    } catch (error) {
      console.log(error);
    }
  };

  const getData = async key => {
    try {
      const data = await AsyncStorage.getItem(key);
      if (data !== null) {
        console.log(data);
        return data;
      }
    } catch (error) {
      console.log(error);
    }
  };

then call getData with the key name like you stored your value wherever you want and set the key to a state value.

Store the value:

storeData("authStatus", the value);

get the value:

  await getData("authStatus") 
    .then((data) => data)
    .then((value) => this.setState({ authStatus: value }))
    .catch((err) => console.log("AsyncStorageErr: " + err));

Upvotes: 1

Related Questions