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?