I need to access the token so I can utilize it in other places in my application. There is a scope issue I am running into, and I have set a variable outside of the function (I have seen that in other use cases it works, if you return to it.)
let myToken;
const getToken = async function () {
try {
const fetchToken = await fetch(
'https://api.website.com/v1/authenticate',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'username123',
password: 'password123',
}),
}
);
const tokenData = await fetchToken.json();
return (myToken = tokenData.data.token);
} catch (err) {
console.error(err);
}
};
getToken();
console.log(myToken);
Undefined is returned.
Thanks for taking a look.