-3

I have a code like this and the console.log(token) shows undefined.

  var token;
  store.get('userTokens').then(res => {
    token = res.idToken.jwtToken;
    console.log(res.idToken.jwtToken);
  });
  switch (type) {
    case 'get':
      console.log(token);
      Axios.get(baseUrl + url, {
        headers: {
          Authorization: `Bearer ${token}`,
          extraHeaders,
        },
      })
        .then(res => {
          console.log(res);
          return res;
        })
        .catch(err => {
          console.log(err);
          return err;
        });
      break;
  }
  • 3
    because you havent defined it you have just declared it, async is still in progress... – EugenSunic Aug 15 '20 at 12:08
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Aluan Haddad Aug 15 '20 at 12:13

2 Answers2

3

You would need to move the switch statement to a place after the promise from store.get is resolved (or rejected).

  var token;
  store.get('userTokens').then(res => {
    token = res.idToken.jwtToken;
    switch (type) {
      case 'get':
        console.log(token);
        Axios.get(baseUrl + url, {
          headers: {
            Authorization: `Bearer ${token}`,
            extraHeaders,
          },
        })
        .then(res => {
          console.log(res);
          return res;
        })
        .catch(err => {
          console.log(err);
          return err;
        });
      break;
    }
  });

Or you could use await to wait for the store.get function to return res

Kunal Kukreja
  • 737
  • 4
  • 18
1

You must be careful of using data coming from ajax call outside of the ajax callback method. The request is asynchronous where often your request hasn't finished but you're already trying to use the variable that stores the response data.

Since you're using react, try to create a state variable called token and then listen to changes on it before using your switch statement.

As Others have advised, with your current scenario you will need to do this:

var token;
store.get('userTokens').then(res => {
    token = res.idToken.jwtToken;
    // Check if token has value before you use it.
    if(token)
    {
        switch (type) {
            case 'get':
                console.log(token);
                Axios.get(baseUrl + url, {
                    headers: {
                        Authorization: `Bearer ${token}`,
                        extraHeaders,
                    },
                })
                .then(res => {
                    console.log(res);
                    return res;
                })
                .catch(err => {
                    console.log(err);
                    return err;
                });
          break;
        }
    }
});

To avoid errors, always check if the is data from response and then perform your operations.


Since you're using React, I would advise you do it using react features to your advantage. For example using React Hooks, check this approach:

function SomeComponent ()
{
  const [token, setToken] = useState("");

  // do something when token value was changed 
  useEffect(()=> {
    if(token)
      performSwitchOperations(token); // pass your state variable token
  },[token])
  
  // Function to be executed when token is retrieved
  const performSwitchOperations =(token) =>
  {
    switch (type) {
      case 'get':
        console.log(token);
        Axios.get(baseUrl + url, {
          headers: {
            Authorization: `Bearer ${token}`,
            extraHeaders,
          },
        })
          .then(res => {
            console.log(res);
            return res;
          })
          .catch(err => {
            console.log(err);
            return err;
          });
        break;
    }
  }
  
  const performAjaxRequest = () =>
  {
    return store.get('userTokens').then(res => 
    {
      console.log(res.idToken.jwtToken);
      setToken(res.idToken.jwtToken);
    });
  }
}
Mosia Thabo
  • 4,009
  • 1
  • 14
  • 24