To prefeace this, I'm a novice at JS programming, I'm a .net guy, so this may be the source of the cofusion.
On my PageLayout.vue, in the created event, I'm trying to do authentication stuff (using okta)
The error I'm getting is:
Uncaught (in promise) TypeError: _this.$auth.getAccessToken(...).then is not a function at eval (PageLayout.vue?66f1:87)
but right above the call to getAccessToken, the call to this.$auth.GetUser() is a success, we are literally in the then call of that method.
Does the this change scope in the then call?
Then why does this.$store.commit('SET_OKTA_USER', user) succeed right before it?
created() {
this.$store.commit('SET_LOADING_APP', true)
this.$auth.getUser().then((user) => {
// Set Okta user
if (user == null && user == undefined) {
// no user
this.$store.commit(
'SET_RESPONSE_MSG',
'Okta user is null or undefined.'
)
this.$store.commit('SET_RESPONSE_TYPE', 'error')
} else {
// store user
this.$store.commit('SET_OKTA_USER', user)
// store token
this.$auth.getAccessToken().then((token) => { //<---------blow up here saying it's not a function.
this.$store.commit('SET_ACCESS_TOKEN', token)
localStorage.setItem('token', JSON.stringify(token))
apiClient.defaults.headers.common.Authorization = `Bearer ${token}`
})
// adName
const adName = user.preferred_username.substr(
0,
user.preferred_username.indexOf('@')
)
this.$store.commit('SET_AD_NAME', adName)
this.getUserInfo(adName)
}
})
},
I'm at a loss as to why the code above it is valid, but the getAccessToken is not.
ifi paste
const accessToken = this.$auth.getAccessToken();
if (accessToken != undefined)
{
this.setUserToken(accessToken);
this.getUserInfo(this.$store.state.adName);
}
Immediately above the this.$auth.getAccessToken().then... it appears to work fine.
I feel pretty confident that this is a variable scope issue, but I'm not entirely sure how to describe it.
Basically the anonymous function that's being passed to then is creating a new private scope,
this.$auth.getUser().then((user)=>{
//this no longer exists like you expect it to
});
The simplest solution that occurs to me would be to change your created() method to async so that you can rework it to something like this:
async created(){
let user = await this.$auth.getUser();
//do some stuff
let token = await this.$auth.getAccessToken();
}