A
A
Alexander Sharomet2018-10-05 14:12:13
JavaScript
Alexander Sharomet, 2018-10-05 14:12:13

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. но данных то нет.
  }
};

store.js
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));
        }
    }

5bb75002f3b76150209553.png
How to implement it correctly? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-10-05
@sharomet

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);
},

And where do you access the properties of this user - check for its presence. If in the template - v-if="user", if in the code of some method - . if (this.user) {

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question