0

I am attempting to build a MEVN stack authentication page that returns information on the currently logged-in user. Upon logging in, the router re-directs to the Home.vue while passing the username to the Home.vue as a prop.

onSubmit method in Login.vue

<script>
  methods: {
    onSubmit (evt) {
      evt.preventDefault()
      axios.post(`http://localhost:3000/api/auth/login/`, this.login)
        .then(response => {
          localStorage.setItem('jwtToken', response.data.token)
          this.$router.push({
            name: 'BookList',
            params: { username: this.login.username }
          })
        })
        .catch(e => {
          this.errors.push(e)
        })
      },
      register () {
        this.$router.push({
          name: 'Register'
        })
      }
    }
  }
  </script>

A Vuex action is then dispatched in the Home.vue component, which passes the username to an action handler in store.js

Instance in Home.vue

import axios from 'axios'
import { mapState } from 'vuex'
export default {
  name: 'BookList',
  props: ['username'],
  data () {
    return {
      errors: []
    }
  },
  computed: mapState([
    'users'
  ]),
  created () {
    this.$store.dispatch('setUsers', this.username)
  }
}
</script>

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    users: [],
  },
  mutations: {
    setUsers: (state, users) => {
      state.users = users
    }
  },
  actions: {
    setUsers: async (context, username) => {
      let uri = `http://localhost:3000/api/auth/currentuser?username=${username}`
      const response = await axios.get(uri)
      context.commit('setUsers', response.data)
    }
  }
})

The store requests the username of the logged-in user from an Express route set up to search for the logged-in user based on a URL with username as a query:

http://localhost:3000/api/auth/currentuser?username=${username}

Express Route

router.get('/currentuser', function(req, res) {
  let params = {},
  username = req.query.username
  if (username) {
     params.username = username
  }
  User.find(params, function (err, users) {
    if (err) return next(err);
    res.json(users);
  });
});

The username of the logged-in user is successfully retrieved and returned to the template:

      <table style="width:100%">
        <tr>
          <th>Logged in User</th>
        </tr>
        <tr v-for="user in users" :key="user._id">
          <td>{{ user.username }}</td>
        </tr>
      </table>

HOWEVER...as soon as I refresh the browser, the username disappears. Any idea why the name does not stay on the screen? Does it have something to do with the username being passed into Home.vue as a prop? Instead of passing the username prop all the way to:

http://localhost:3000/api/auth/currentuser?username=${username}

...is there perhaps another way that I could pass the username of the logged-in user as a query in the URL?

UPDATED STORE.JS

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VuexPersistence from 'vuex-persist'

const vuexLocal = new VuexPersistence({
  storage: window.localStorage
})

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    users: [],
  },
  mutations: {
    setUsers: (state, users) => {
      state.users = users
    }
  },
  actions: {
    setUsers: async (context, username) => {
      let uri = `http://localhost:3000/api/auth?username=${username}`
      const response = await axios.get(uri)
      context.commit('setUsers', response.data)
    }
  },
  plugins: [vuexLocal.plugin]
})

2
  • You are passing the username to your BookList route via params. How does this become a prop in Home.vue? What does the BookList route look like? Commented Dec 5, 2019 at 22:54
  • I suspect you are not persisting username anywhere... Commented Dec 5, 2019 at 23:05

1 Answer 1

2

In Vue/Vuex, the state is wiped clean once you refresh the page or dump the cache. If you want to persist the data, you have a few choices.

If you store them locally, it's a good idea to use Tokens or another security measure if you're worried about what users could do with locally stored data.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi @Arc, I attempted to utilize the vuex-persist plugin that you recommended in order to persist the data. See the UPDATED STORE.JS example above. I installed the plugin according to the GitHub instructions, and imported it into Vuex. Under Application in the browser inspection tool, I can see the data pushed into localstorage value under a local storage key named vuex. However, once I refresh the page, the localstorage value for the user goes blank, while also disappearing from the screen in the app. What should I do at this point to persist the username?
If you're still having problems as you mentioned in the other thread, I can only recommend ensuring your setup is correct. If localStorage isn't persisting through refresh, that must be a browser error (can you reproduce this in other browsers?) or a configuration error (is Vuex Persist set up properly?). npmjs.com/package/vuex-persist#steps
Hi Arc, would you be in a position to take a look at another MEVN stack issue? stackoverflow.com/questions/60108257/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.