0
votes

weird question but i don't find an answer anywhere..

I return user data from an API call to Vuex. I save my user object into the Vuex state, along with a Token. (User object and Token are created and send back from Server to Vuex at the same time.)

Everything runs perfect and on the initialization of the component i fetch with a getter the user name etc.

But when i refresh i loose the user object from the state. But, i do not loose the Token. Which is weird cause i create them and return them together.

The question is, how can i keep the user in the state until i logout?

  • I don't need to keep them in localStorage or inside a cookie cause they are sensitive data (user). I just want to get them through a getter from my store. Which is the correct way to do it. So vuex-persist is not an option..

Below you see my code:

store.js:

state: {
    status: '',
    token: localStorage.getItem('token'),
    user: {}
},
mutations: {
    auth_success(state, { token, user }) {
    state.status = 'success';
    state.token = token;
    state.user = user;
},
actions: {
    login({ commit }, user) {
      return new Promise((resolve, reject) => {
        commit('auth_request');
    axios({
          url: 'http://localhost:8085/login',
      data: user,
      method: 'POST'
        .then((resp) => {
           const token = resp.data.token;
           const user = resp.data.user;

           axios.defaults.headers.common['Authorization'] = token;

           commit('auth_success', { token, user });
         })
         .catch((err) => {
           commit('auth_error');
           localStorage.removeItem('token');
           reject(err);
        });
  }
},
getters: {
 isLoggedIn(state) {
  return state.token;
},
getUser(state){
  return state.user;
}

User.vue:

<template>
  <v-container>
    <v-layout row wrap>
      Welcome {{this.user.fullName}}
    </v-layout>
  </v-container>
</template>
<script>
 export default {
   data: function() {
    return {
    user: {}
   }
  },
   mounted() {
    this.getUser();
  },
 methods: {
    getUser() {
      return (this.user = this.$store.getters.getUser);
    }
 }
}
</script>

So to sum up: Token stays in Vuex, user data does not. How to keep them in state without local Storage or cookies?

Any help would be greatly appreciated!

1
The getUser computed property should not be modifying reactive state; did you mean for it to be a method?Decade Moon
Really sorry, i wrote it wrong. It is a method, i will edit my question. Thanks!Alexander F
Vue stores data in the memory, when you refresh the page, it is expected to lose all the memory. You can use the router guard, check it at beforeRouteEnter, if vuex does not have user object, call the getUser() again. Take a look at this demo github.com/gothinkster/vue-realworld-example-app/blob/master/…Sang Dang
@SangĐặng So you say that there is no way to do it.. getUser() get's what exists in the state. Which gets filled once you login. Only then.Alexander F
The answer below explains pretty good what I wanted to say.Sang Dang

1 Answers

2
votes

Basically, as Sang Đặng mentioned, if you want to have user data in your vuex (without storing it on the user side) you need to fetch them after every refresh. Refreshing the page means that whole Vue application (and your Vuex state) is removed from the memory (user's browser), which causes that you lose your current store data. token is also removed from the memory, but you load it on your store initialisation:

state: {
  token: localStorage.getItem('token'),
  ...
}

Because of this you are seeing token "kept" in store, while other user data not. There are many ways to fetch user data after refresh - like mentioned beforeRouteEnter. Basically if you want to fetch them on the application load, so you can use Vue.created hook for example. You can also use lazy-loading in your getUser method - if there is no user data - fetch them from your API. Here you can read more about authentication patterns in SPA - for example using OAuth.