I have a create user page. When I hit create user button it works fine, it creates the new user and redirect me to the page displaying all the users. But I noticed that, in order to see the last user (the one just created) here (in the page displaying all the users) I need to refresh the page.
Here the code, in createUser.vue:
methods: {
onSubmit() {
const userData = {
username: this.form.username,
email: this.form.email,
password: this.form.password
}
try {
this.userData = createUser(userData)
this.$message('User created!')
this.$router.push({
path: '/users-list'
})
} catch (err) {
console.log('Error in creating user: ', err)
}
}
}
And in the users-list.vue:
created() {
this.$store.dispatch('user/setUsers')
const users = this.$store.getters.users
this.users = users
console.log("ALL USERS WITH GET PROFILE IN LISTA: ", users)
console.log('store in lista utenti: ', this.$store.state)
this.totalRows = this.users.length
},
Is there a way to refresh the pushed route before it gets rendered? Any lifecycle hooks I am missing?
Or maybe use a watch to spot change state of users
(which in the store contains all the users created)?
I am currently checking for this solution as it seems to be the most appropriate to me, but if I am missing something about lifecycle hooks this option can be good to.
If anyone has an answer before me, please share :) Thanks x
UPDATE
I am back to this issue, I think the best way is the one indicated by @ambianBeing createUser().then(res => /*do stuff*/)
do stuff = ?
So, in the user module I created a new mutation and a new action (the one to be dispatched inside then() -before pushing the new route
.then(() => {
....
this.$store.dispatch('user/addUser')
this.$router.push({...})
})
).
The mutation, to kind of push the just created user to the users array, is:
ADD_USER: (state, user) => {
state.users = [user, ...state.users]
},
And the action that commits this mutation is:
addUser({ commit }, users){
commit('ADD_USER', users)
},
But the I get the just created user undefined, here the console.log:
ALL USERS WITH GET PROFILE IN USERS LIST: (18) [undefined, {…}, {…}, {…}, {…}, {…}]
I also tried user instead of users in the commit, but it doesn't work neither.
Anyone knows how to help? Thanks
I wasn't passing a user object to the action …
this.$store.dispatch('user/addUser')
but the action expects to receive one:
addUser({ commit }, user){
commit('ADD_USER', user)
}
N.B. The right action was the one passing user not users.
This solved the issue, and this was the way to do it. I guess. If someone thinks differently, please. Thanks