Recently, I've been working on updating data in a component every time the Vuex state is not null. I have set up API routes with Laravel that return user information once they are logged in.
API routes:
Route::group(['middleware' => ['auth:api']], function () {
Route::get('profil', 'Api\UserController@profil')->name('profile'); // will return user info
}
Vuex:
export default new Vuex.Store({
state: {
token: localStorage.getItem('token') || "",
user: {}
},
getters: {
isAuth: state => {
return state.token != "" && state.token != null
}
},
mutations: {
SET_TOKEN(state, payload) {
state.token = payload
},
SET_AUTH_USER(state, payload) {
state.user = payload
}
}
})
In my App.vue file, in the created method, I commit SET_AUTH_USER with the HTTP response as the payload if the token exists.
App.vue:
<template>
<div id="app-layout">
<section-advices></section-advices>
</template>
<script>
import SectionAdvices from "./SectionAdvices"
export default {
name: "app-layout",
components: {
SectionAdvices
},
created() {
if (this.$store.state.token !== (null || "")) {
this.$http
.get("/profil")
.then(res => {
if (res.status === 200) {
this.$store.commit("SET_AUTH_USER", res.data.data);
} else {
this.$store.commit("SET_AUTH_USER", null);
}
})
.catch(err => {
console.log(err);
});
}
}
}
</script>
Everything seems to be working fine so far. Whenever I refresh the page and there's a token in my local storage, the user object always contains the user information.
SectionAdvices.vue:
<template>
<section class="advices">
<input type="text" v-model="name">
<input type="text" v-model="email">
</section>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
name: "section-advices",
data(){
return{
name: null,
email: null
}
},
computed:{
...mapState(["user"]),
...mapGetters(["isAuth"]),
},
created() {
if(this.isAuth) {
this.name = this.user.name
this.form.email = this.user.email
}
}
}
</script>
Despite having values for name and email in the user object according to Vue Dev tools, both are showing as "undefined" in the SectionAdvices component. Could it be that I'm calling the API in the wrong lifecycle inside App.vue?