I have a token I stored using the sensitive info keychain but when I try to get the token I keep getting either undefined or {"_U": 0, "_V": 0, "_W": null, "_X": null}
My code:
// Get Token from storage
const getToken = async () => await RNSInfo.getItem('token', {});
const token = getToken();
console.log(token);
When I write a function and include above code inside it I can successfully return it but I need the token for code outside that function
// check if post is liked
const checkIsLiked = async () => {
const token = await getToken();
try {
axios
.get(url, {
headers: {
'Content-Type': 'application/json',
Authorization: 'token ' + JSON.parse(token),
},
})
.then(res => {
const likeValue = res.data;
setIsLike(likeValue);
});
} catch (error) {
console.error(error);
}
};
You may forget to add await
before getToken()
in the first part of code.
const getToken = async () => await RNSInfo.getItem('token', {});
const token = await getToken(); //add 'await' in this line
console.log(token);
If you are using functions which cannot be simply change to asynchronous like useEffect
. You may follow the codes below.
React.useEffect(() => {
const doWhenFocus = async() => {
const token = await RNSInfo.getItem('token', {});
console.log(token);
};
doWhenFocus();
});