Pedro Magalhães
Pedro Magalhães

Reputation: 83

Best way to define user session data in Vue using Laravel and Inertia

I'm developing a app with a dynamic menu using Laravel, Vue and Inertia.

In order to pass the session information about the menu (which itens should be showed, icons, etc) and user data (avatar and name), actually i use the HandleInertiaRequests middleware.

However, this way, all the information is sent in every Inertia request, which, i believe, its far from perfect.

So, it's there some kind of strategy that allows to send the session information only once, preferably, in the login fase?

Upvotes: 2

Views: 1736

Answers (1)

Bikalpa
Bikalpa

Reputation: 118

In this case i'll store user details in vuex from MasterLayout.vue. The layout should be mounted only after user is logged in.

In MasterLayout.vue;

<template>
  ...
</template>

<script>
...
mounted() {
 this.$store.dispatch("setUser");
}
</script>

Now, in auth.js;

export const auth = {
state: () => ({
    user: [],
}),

actions: {
    setUser({ commit }) {
        commit("SET_USER");
    },
},

mutations: {
    async SET_USER(state) {
        await axios
            .get(route("user"))
            .then((response) => {
                state.user = response.data;
            })
            .catch((error) => {
                console.log(error);
            });
    },
},

getters: {
    auth(state) {
        return state.user;
    },
  },
};

Now, in Avatar.vue component;

  <template>
    //do anything with data
    {{auth.name}}
    {{auth.email}}
  </template>

  <script>
    computed: {
     ...mapGetters(["auth"]),
    },
  </script>

Upvotes: 1

Related Questions