I have an asynchronous API call that returns a promise containing the username of the currently logged in user. I am able to extract the username by using the .then function. However, when I try to access the username from outside the .then function, I always get "undefined."
const getUsername = async () => {
try {
const res = await fetch("http://localhost:1234/username", {
method: "POST",
headers: { jwt_token: localStorage.token }
});
const parseRes = await res.json();
return parseRes;
} catch (err) {
console.error(err.message);
}
}
var username;
function setUsername(uname) {
username = uname;
}
const p = getUsername();
p.then(value => {
setUsername(value.username);
});
console.log(username); // returns "undefined"
I have tried doing this in multiple ways such as: directly assigning to the username variable, writing a function to set the username variable (as shown in this example), and putting my return function (for the react component) inside my .then function, which bricks the whole app.
How would I go about retrieving the result of this API call?