Reputation: 3444
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?
Upvotes: 4
Views: 10743
Reputation: 1003
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
Upvotes: 3
Reputation: 63059
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.
Upvotes: 13