Asynchronous storage doesn't work to install or install React Native
I am trying to do user authentication with an async store to decide which screen will be displayed, so when I get data from the async store I get back to me undefined Can anyone help me?
My code:
var login;
AsyncStorage.getItem("login").then((value) => {
login = value;
}).done();
alert(login);
My code:
const insert_user = (username) => {
AsyncStorage.setItem("login", username);
Toast.show({
supportedOrientations: ['portrait', 'landscape'],
text: `User registered with success`,
position: 'bottom',
buttonText: 'Dismiss'
});
}
+3
source to share
1 answer
alert(login);
will always be undefined because AsyncStorage.getItem is asynchronous in nature, i.e. the (login) alert is called first before you get 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 link
- AsyncStorage.getItem will return a promise: https://www.promisejs.org/
- Async vs Sync: https://www.pluralsight.com/guides/front-end-javascript/introduction-to-asynchronous-javascript
+5
source to share