Im trying to make the user authentication using async storage to decide which screen will be rendered so when i get the data from the async storage returns to me undefined can someone help me?
My get code:
var login;
AsyncStorage.getItem("login").then((value) => {
login = value;
}).done();
alert(login);
My set code:
const insert_user = (username) => {
AsyncStorage.setItem("login", username);
Toast.show({
supportedOrientations: ['portrait', 'landscape'],
text: `User registered with success`,
position: 'bottom',
buttonText: 'Dismiss'
});
}
alert(login);
will always be undefined because AsyncStorage.getItem is asynchronous in nature meaning alert(login) is called first before you receive the value from AsyncStorage.getItem
AsyncStorage.getItem("login").then((value) => {
alert(value); // you will need use the alert in here because this is the point in the execution which you receive the value from getItem.
// you could do your authentication and routing logic here but I suggest that you place them in another function and just pass the function as seen in the example below.
});
// a function that receives value
const receiveLoginDetails = (value) => {
alert(value);
}
// pass the function that receives the login details;
AsyncStorage.getItem("login").then(receiveLoginDetails);
Further reference