Home > Software design >  user info is not loading in vue component after login
user info is not loading in vue component after login

Time:05-12

I am using localstorage to save user info after a successful login. Then I want to put a v-if condition to filter whether the user is logged in or not. But the problem is, the localStorage returning null while I am trying to parse it in components. I am sharing the codes from component here :

data() {
    return {
        currentUser : {}
    }
},

mounted() {
    this.currentUser = localStorage.getItem('userInfo')
}

From the Template :

<span v-if="currentUser" >{{ currentUser.name 
}}</span>

From console :

enter image description here

CodePudding user response:

You can simply achieve that by just considering below two points :

  • While storing the data in localStorage, store it as a string. In the below demo I will use JSON.stringify() to convert the userInfo object into a string.
  • While fetching the data from localStorage, parse it using JSON.parse()

Working Demo :

new Vue({
  el: '#app',
  data: {
    userInfo: null
  },
    mounted() {
    this.getUserInfo();
  },
  methods: {
    saveUserInfo() {
        const userInfo = {
        id: 1,
        name: 'alpha'
      }
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    getUserInfo() {
        this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p> <strong>UserName :</strong> {{ userInfo?.name }} </p>
  
  <button type="submit" @click="saveUserInfo">
   Save User Info
  </button>
</div>

CodePudding user response:

localStorage store as key-value pair; and the value is type of string, you should parse it to JSONObject

  • Related