Answer the question
In order to leave comments, you need to log in
How to properly get getters from vuex if it is called asynchronously?
Hello.
First, I call the SET_USERS action in the mounted method, it waits until the data is returned from the database, at the same time getter GET_USER_BY_ID is called - it turns out that the state is still empty and the getter is already trying to pull data from it.
And naturally the error that there is no data falls out.
component.vue
export default {
data() {
return {
user: "",
};
},
computed: {
...mapGetters(["GET_USER_BY_ID"]) // Проблема в этом асинхронном запросе
},
methods: {
...mapActions(["SET_USERS"])
},
mounted() {
this.SET_USERS(); // Запускаем action
this.user = this.GET_USER_BY_ID(this.$route.params.id); // Записываем данные в свойство user. но данных то нет.
}
};
state: {
users: [], // Массив пользователей
},
getters: {
GET_USER_BY_ID: (state) => id => { // Тут я получаю пользователя из state по id
return state.users.find(user => user.id === id);
}
},
mutations: {
SET_USERS(state, users) { // Тут получаем данные из action и загоняем их в state (массив)
state.users = users;
}
},
actions: {
SET_USERS({commit, state}) {
db.collection('users').get().then(users => { // Получаем данные из базы
commit('SET_USERS', users.docs.map(doc => { // Передаём данные в mutation
let data = doc.data();
return {
id: doc.id,
firstName: data.firstName,
lastName: data.lastName,
email: data.email,
};
}));
}).catch(err => console.log(err));
}
}
Answer the question
In order to leave comments, you need to log in
Make user a computed property so you don't have to update it manually on mounted or whatever:
user() {
return this.GET_USER_BY_ID(this.$route.params.id);
},
v-if="user"
, if in the code of some method - . if (this.user) {
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question