I have implemented a login form that utilizes an axios interceptor to manage the response from the API, whether it is successful or not.
After receiving the response, it is directed to my vuex store where the user's credentials are stored.
However, when I try to log the response in my Login component, I do not see the expected fields such as data
, status
, and headers
. Instead, I encounter something different.
https://i.sstatic.net/kIT6k.png
I am wondering if there is a way to validate that the data is properly stored in the Vuex store before proceeding with the user login process?
Currently, my workaround involves utilizing a setTimeout
for 3 seconds and then invoking a state getter function to retrieve the user data. While this solution works, I believe there must be a more efficient approach available.
Login.vue
onClickLogin() {
const userToLogin = {
username: this.loginForm.username,
password: this.loginForm.password
};
const response = UsersModule.login(userToLogin);
console.log("response", response); // displays unexpected data structure
if (response) {
this.$router.push("/");
}
}
Axios Request Class
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_URL,
timeout: 5000
});
service.interceptors.response.use(
response => {
return response.data;
},
error => {
Message({
message: error.message || "Error",
type: "error",
duration: 5 * 1000
});
return Promise.reject(error);
}
);
Vuex Users Login Function
@Action({ rawError: true })
async login(usersSubmit: UserSubmit) {
const response: any = await loginUser(usersSubmit);
if (typeof response !== "undefined") {
const { accessToken, username, name } = response;
setToken(accessToken);
this.SET_TOKEN(accessToken);
this.SET_USERNAME(username);
this.SET_NAME(name);
}
}
API Class - Calls Axios Request via Vuex Store
export const loginUser = (data: UserSubmit) => {
return request({
url: "/auth/login",
method: "post",
data
});
};