Async storage not working to set or get on React Native
The complete to use AsyncStorage with async and await is the following
import { getItem as localStorageGetItem, setItem as localStorageSetItem } from 'services/localStorage';
async loginHandler (){
localStorageSetItem(ACCESS_TOKEN, response.accessToken);
var token = await localStorageGetItem(ACCESS_TOKEN);
}
localStorage.js file
import AsyncStorage from '@react-native-community/async-storage';
export const getItem = async(item) => {
try {
const value = await AsyncStorage.getItem(item);
return JSON.parse(value);
} catch (error) {
return null;
}
};
export const setItem = async(item,value)=>{
try {
await AsyncStorage.setItem(item, JSON.stringify(value));
} catch (error) {
console.log("SetItem error ",error)
return null;
}
}
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
import { AsyncStorage } from 'react-native';
AsyncStorage.setItem('mobileNumber', phoneNumber.number);
AsyncStorage.getItem('mobileNumber', (error, result) => {
this.setState({
loginMobileNo: result,
});