I am creating an App that implements JWT using Vue + Vuex,
Every thing works fine until I used localStorage.
Here's my code:
store.js
import constants from './constants';
*state*
state = {
token: constants.loginAstoken || constants.token
}
*mutation*
[UPDATE_TOKEN]: (state, {token, sub}) => {
if(!sub) constants.setToken(token);
else constants.setLoginAsToken(token);
token = constants.token;
axios.defaults.headers.common["Authorization"] = "Bearer " + state.token;
}
constants.js
export function setToken(token) {
localStorage.setItem('token', token);
}
export function loginAsToken(token) {
localStorage.setItem('login-as-token', token);
}
export const token = localStorage.getItem('token') || "";
export const loginAsToken = localStorage.getItem('login-as-token') || "";
Now as I consume my API, and it returned the correct token but inside the mutation state.token
is still null
.
Is there any thing that I've missed or is it just the limitation?
anyway i've turned strict:true
but after reading the strict mode there's no restriction for it in using side effects(maybe? to my understanding) in mutation
any answer would be greatly appreciated
First problem the mutation function takes only 2 params ( state and payload ) DOC, you re passing a third one that will be undefined. To fix this use the payload as object like:
[UPDATE_TOKEN]: (state, { token, sub }) => {
Second problem you re changing the token param value instead of the state:
[UPDATE_TOKEN]: (state, token="", sub="false") => {
if(!sub) constants.setToken(token);
else constants.setLoginAsToken(token);
token = constants.token; <====
CHANGE TO
state.token = token;
axios.defaults.headers.common["Authorization"] = "Bearer " + state.token;
}