R
R
Rostislav2021-02-02 01:45:02
Vue.js
Rostislav, 2021-02-02 01:45:02

How in the child component to find out that the asynchronous data loading has ended?

There is a product route, which contains the id with the product in the url

{
    path: '/product/:code',
    props: true,
    name: 'product',
    component: () => import('../views/Product'),
    meta: { scrollToTop: true },
  },


In App.vue I am querying all products from the DB, which is just a db.json file:
created() {
  this.$store.dispatch('GET_PRODUCTS');
}


Store
async GET_PRODUCTS({ commit }) {
try {
  const response = await axios.get('http://localhost:8080/db/db.json');
  commit('setProducts', response.data);
} catch (error) {
  console.log(error);
}
},


How to find out in Product.vue that the data has already been loaded and add the current product to the store.
Now I do it in created, but sometimes the data does not have time to load and an error occurs.

created() {
  this.$store.dispatch('setProduct', this.code);
}


Add product to store action:
setProduct({ state, commit }, code) {
      const products = state.products;
      let product = null;

      Object.values(products).some((val) => {
        product = val.find((item) => item.code === +code);
        return product;
      });

      const size = product.meta[0];

      commit('setProduct', product);
      commit('setSizeAndCost', size);
    },

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-02-02
@rostik32

In App.vue I am querying all products from db

If the products need to be available everywhere, maybe then it's worth getting them first, and then initializing the application:
store.dispatch('GET_PRODUCTS').then(() => {
  new Vue({ ... });
});

??
If you answer directly to what was asked, set a watch on the value in the storage:
watch: {
  '$store.state.products': {
    immediate: true,
    handler(products) {
      if (products) {
        // можно что-то сделать
      }
    },
  },
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question