简体   繁体   中英

How to init the store with data from the localstorage?

I an learning Vue (3) and vuex.

I have this store:

export default new Vuex.Store({
      state: {
        user: null
      },
    
      mutations: {
        setUserData (state, userData) {
          state.user = userData
          console.log('userData')
          console.log(userData)
          localStorage.setItem('user', JSON.stringify(userData))
          axios.defaults.headers.common.Authorization = `Bearer ${userData.access_token}`
        },
    
        clearUserData () {
          localStorage.removeItem('user')
          location.reload()
        }
      },
    
      actions: {
        login ({ commit }, credentials) {
          return axios
            .post('/login', credentials)
            .then(({ data }) => {
              commit('setUserData', data)
            })
        },
    
        logout ({ commit }) {
          commit('clearUserData')
        }
      },
    
      getters: {
        isLogged: state => !!state.user,
        user: state => state.user
      },

And in a component, I want to get the user connected like this:

<script>

import { mapGetters } from 'vuex'
export default {

  computed: {
    ...mapGetters({
      user: 'user'
    })
  },

  data () {
    return {
      stores: [],
      loading: false
    }
  },

  created () {
    console.log('toto')
    console.log(this.user.id)
    this.getStores()
  },

The first time the user logs in, it works fine: I can see the user.id in the console.

But when I refresh the page (and the user is connected), the user.id is undefined.

My question is: how to put the user in the store if the localstorage contains the user?

You can load the initial state value directly from localStorage :

state: {
   user: JSON.parse(localStorage.getItem('user'))
},

Since you used JSON.stringify when setting, use JSON.parse when getting.

A more generic solution could be to use a plugin that persists the entire state to local storage, that way you don't have to deal with individual values and your whole application is still available when a user hits refresh:

https://www.npmjs.com/package/vuex-persist

If you want more granular control and at the same time the ability to store more complex data type than strings, have a look at localForage:

https://www.npmjs.com/package/localforage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM