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'
});
}
Using the setItem() method // React Native component const value = { name: "Chimezie", job: "Software Developer" }; const storeUser = async () => { try { await AsyncStorage. setItem("user", JSON. stringify(value)); } catch (error) { console. log(error); } };
Deprecated. Use one of the community packages instead. AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.
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
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