Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async storage not working to set or get on React Native

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'
  });
}
like image 979
Luiz Fernando Sousa Camargo Avatar asked Jul 27 '17 03:07

Luiz Fernando Sousa Camargo


People also ask

How do you implement async storage in React Native?

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); } };

Is React Native async storage deprecated?

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.


1 Answers

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

  • 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
like image 50
Sharlon M. Balbalosa Avatar answered Oct 01 '22 04:10

Sharlon M. Balbalosa