Insight
I am attempting to utilize AsyncStorage to store a Token after a successful login. The token is obtained from the backend as a response once the user clicks on the Login button. Upon navigating to the ProfileScreen, I encounter difficulties in retrieving the saved token.
Challenge
Upon trying to retrieve the item in the ProfileScreen and logging it to the console, I discover that I am getting a Promise object filled with nested objects, within which I can locate my desired value. How can I extract this value effectively?
Solution
Utilities/AsyncStorage.js (Contains helper functions for storing and retrieving items)
const keys = {
jwtKey: 'jwtKey'
}
const storeItem = async (key, item) => {
try {
var jsonOfItem = await AsyncStorage.setItem(key, JSON.stringify(item));
console.log('Item Stored !');
return jsonOfItem;
} catch (error) {
console.log(error.message);
}
};
const retrieveItem = async key => {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
console.log('Item Retrieved !');
return item;
} catch (error) {
console.log(error.message);
}
return;
};
LoginScreen.js (After clicking on the login button, receiving a token response from backend)
const LoginScreen = ({componentId}) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const loginPressed = async () => {
await axios
.post('localhost', {
email,
password,
})
.then(function(res) {
console.log(res);
storeItem(keys.jwtKey, res.data.token);
push(componentID, views.profileScreen());
})
.catch(function(error) {
console.log(error);
});
};
ProfileScreen.js (Attempting to retrieve and use the token on this screen)
const ProfileScreen = ({componentID}) => {
let testingAsync = retrieveItem(keys.jwtKey);
console.log(testingAsync);
The log displays a promise object containing nested values.
Promise{_40:0, _65:0 , _55:null, _72:null}
The actual token value can be found within the _55 property of the object.