N
N
Nik_Set_72018-04-03 13:26:23
Vue.js
Nik_Set_7, 2018-04-03 13:26:23

Vuex: Why is it returning an empty object?

I use vuex to store, retrieve and return data to components. Got $store, got data.
The Vuex documentation states that it is desirable to use getters to get data.

const store = new Vuex.Store({
  state: {
    news: [],
  },
  getters: {
        news: (state) => state.news
  },
...
});

export default {
...
        computed: {
            news () {
                console.log(this);
                console.log(this.$store.getters.news);
                return this.$store.getters.news;
            }
        },
...
}

However, an "empty" object with a zero length is displayed in the console under the name:
[__ob__: xe]
At the same time, this contains information on news in $store. What could be the reason for the error?
UPD:
The error turned out to be trivially simple. Because I make an ajax request, then the response does not come instantly, while rendering, etc. occurs immediately.
Therefore, it turns out that on the one hand, there is information about the news, because the answer came and changes were made to vuex. But at the time of rendering, there was no data, so the console did not have information about the variable / array I needed. At least that's how I understand the problem.
To solve it, you need to:
- transfer receiving by ajax from actions directly to the component, while doing vuex state changes through mutations
- use async functions or modules like vue-async-computed

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Velko, 2018-04-03
@Nik_Set_7

Why make a similar getter at all, which returns just a state from the store?
If the same you can get through:

...mapState({
  news: state => state.news,
});

or this.$store.state.news
UPD: In general, it would be more correct to create an action in the same store, which will fetch the data and fill the array. Well, use async / await, for example. Like like this:
const actions = {
  async fetchNews({ commit }) {
    // Стреляете запрос в нужный эндпоинт
    const { data } = await axios.get('http://your.api.endpoint');
    
    if (data.result) {
      // Записываете новости в стору с помощью мутации
      commit(SET_NEWS, data.data);
    } else {
      // Обрабатываете ошибку, если не удалось получить новости
    }
    
    return data;
  },
};

Well, in the component itself, you get a state store, as I described above. Well, if necessary, render the block with the news via . v-if="news.length > 0"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question