[Vuejs]-Laravel & Vue: Initialise Authentication from Store before rendering any components using

0đź‘Ť

âś…

Here are couple of issues i see in your code:

Vuex Mutations are synchronous and Vuex actions are asynchronous

Ref: Vuex Documentation on actions

Your business logic must go in actions as they are asynchronous (i.e axios calls) and your data update/manipulation should go in mutations

In your “AUTH_USER” mutation you are making axios call which should be in your “authUser” action instead.

\\ Your SET_USER mutation could look like below 

SET_USER(state, payload) {

  \\ User data will be passed in 2nd param (i.e payload) 
  state.user = payload

  \\ if we get the data in payload then set loggedin 
  \\ variable to true otherwise false
  state.loggedin = (payload) ? true : false

}

\\ Your authUser vuex action could look like below, returning the promise 
authUser: ({ commit }) => {
   return axios
     .get("api/register", {
        headers: {
          Authorization: `Bearer ${localStorage.usertoken}`
        }
      })
      .then((response) => {
        commit("SET_USER",response.data.user);                
      })
      .catch((err) => {
        console.log(err, "Konnte keine Daten abrufen");
      });

}

Leave a comment