I am trying to retrieve the user from my JWT token which is being served from a Django-Rest API endpoint, /get-token/
and store the user in my Vuex Store.
I don't have an endpoint set up to return the logged in user
, and while this could be a potential solution I see no reason to do that instead of retrieving the user from the JWT token.
I've tried retrieving the user directly from the JSON token via this.$store.commit('setAuthUser', response.data.user)
and response.data.user.username
Login.Vue
axios.post(this.$store.state.endpoints.obtainJWT, payload)
.then((response) => {
this.$store.commit('updateToken', response.data.token)
this.$store.commit('setAuthUser', response.data.user) -------This line is not working
console.log(response.data)
})
store.js
export default new Vuex.Store({
state: {
authUser: {},
isAuthenticated: false,
jwt: localStorage.getItem('token'),
endpoints: {
obtainJWT: 'http://127.0.0.1:8000/get-token/',
refreshJWT: 'http://127.0.0.1:8000/refresh-token/',
baseUrl: 'http://127.0.0.1:8000/main/api/',
}
},
mutations: {
setAuthUser(state, {
authUser,
isAuthenticated
}) {
Vue.set(state, 'authUser', authUser)
Vue.set(state, 'isAuthenticated', isAuthenticated)
},
updateToken(state, newToken) {
localStorage.setItem('token', newToken);
state.jwt = newToken;
},
removeToken(state) {
localStorage.removeItem('token');
state.jwt = null;
}
}
});
Expected: Properly retrieved user and stored in Vuex with setAuthUser mutator
Actual: Error Cannot destructure property 'authUser' of 'undefined' or 'null'.