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()
);
}
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With