I have a login service and account profile page and account update form page and when I login I get a token and a user back from the API backend and set the data in the store in a mutation. If I want to update a profile, I go to '/profile/edit' page and submit a form to the server and if the record gets updated on the server I get the updated user record back in the response and set this new user object in the store and redirect to user profile page at '/profile'. So far so good, I can see that the account attributes have changed on the profile page, however, when I refresh the page I get the old user object that I got after logging in so, for some reason, the new user wasn't set properly in the store and I don't understand what is going on. I would appreciate your help. Here is my code:
Store
export default new Vuex.Store({
state: {
auth: {
apiToken: null,
user: {},
}
},
getters,
mutations,
actions
})
Login action
login({ commit }, payload){
axios.post('/api/auth/login', payload)
.then(response => {
commit('authenticateUser', {
token: response.data.api_token,
user: response.data.user
})
localStorage.setItem('token', response.data.api_token)
localStorage.setItem('user', JSON.stringify(response.data.user))
router.push('/')
})
.catch(error => {
commit('showErrorAlert')
})
}
AuthenticateUser mutation
authenticateUser(state, payload) {
state.auth.apiToken = payload.token
state.auth.user = payload.user
state.auth.signedIn = true
}
saveUserProfile action
saveUserProfile({ commit }, payload){
axios.patch('/api/users/' + payload.get('id'), payload)
.then(response => {
commit('saveUserProfile', response.data)
router.push('/profile')
})
.catch(error => {
console.log(response)
})
}
saveUserProfile mutation
saveUserProfile(state, payload){
state.auth.user = payload
console.log(state.auth.user)
# Here I get the updated user from the server with new attribtues
}
In userProfile
component I have a computed
property that fetches the user from the store.
<script>
export default {
computed: {
current_user(){
return this.$store.getters.currentUser;
# here, after updating the account I get the new user record but when I refresh the page, I get the old record.
}
}
}
</script>
When I get redirected to the profile page after updating the account I get the new attributes but after I refresh the page I get the old data. It's weird because I think VueX keeps the data in memory. I can confirm this by logging in and inspecting the state in VueX browser console. I can see that the user record is there. If I then go, for example, to '/dashboard' I can see that the user record is still there. It's pretty weird. Am I going anything wrong?
UPDATE
currentUser getter
currentUser: state => {
return state.auth.user
}