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);
});
}
}