0

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?

sovark
  • 13
  • 4
  • Simply because it reaches `console.log(username)` before the response of call get, there's a way to solve this problem by using `async & await` and surrending it by `IIFE`, Or more simple way by putting `console.log(username)` inside `then` and after that all your code must be inside `then` which is not good for that, use first way! – XMehdi01 Jun 24 '22 at 19:40
  • Hi Sovark. If you're still facing doubts, I created an example on sandbox, using React hooks. [Sandobx](https://codesandbox.io/s/empty-river-1c8vnv) Instead of returning, you can just setState the name at that place only. – Arindam Jun 24 '22 at 20:35
  • I solved this problem by using "useState" from the react library. I created a variable with a setter and set its initial state to an empty string. Then, I called the setter from the promise's .then function. – sovark Jun 30 '22 at 20:41

0 Answers0