Reputation: 69
I am using flask as my backend server. vuex action is not setting token from local storage state to Axios API call. Please help me with what am I missing. currently I am stuck here, this is related to my previous question which I dint get answer so posting again.. Below is my vuex store code:
Vue.use(Vuex);
export default new Vuex.Store({
state: {
// accessToken: JSON.parse(localStorage.getItem('access_token')) || null,
// refreshToken: JSON.parse(localStorage.getItem('refresh_token')) || null,
accessToken: localStorage.getItem('access_token') || null,
refreshToken: localStorage.getItem('refresh_token') || null,
APIData: '',
},
actions: {
refreshToken(context) {
return new Promise((resolve, reject) => {
console.log(context.state.refreshToken);
getAPI.post('/refresh', {
// refresh_token: context.state.refreshToken,
headers: { Authorization: `Bearer ${context.state.refreshToken}` },
})
.then((response) => {
console.log('New access token granted');
context.commit('updateAccessToken', response.data.access_token);
console.log(context.state.accessToken);
resolve(response.data.access_token);
})
.catch((error) => {
console.log('\'error in refresh:\'', error);
reject(error);
});
});
},
}
Upvotes: 0
Views: 236
Reputation: 1229
Here is an example that I built with a simplified Vuex store and Vue component in order to demonstrate the functionality.
/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
accessToken: '',
localStorage: window.localStorage
},
getters: {
getTokenFromLocalStorage: state => {
return state.localStorage.getItem('accessToken');
}
},
mutations: {
storeTokenInLocalStorage(state, newToken) {
state.accessToken = newToken;
state.localStorage.setItem('accessToken', newToken);
}
}
})
VuexLocalStorage.vue
<template>
<div class="vuex-local-storage">
<div class="row">
<div class="col-md-6">
<button class="btn btn-secondary" @click="getAccessToken">Get Access Token</button>
<h5>{{ accessToken }}</h5>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
accessToken: ''
}
},
methods: {
getAccessToken() {
this.accessToken = this.$store.getters.getTokenFromLocalStorage;
}
},
created() {
// Store initial access token
this.$store.commit('storeTokenInLocalStorage', 'access-token');
}
}
</script>
Upvotes: 1