R
R
Rostislav2021-01-27 22:34:11
Vue.js
Rostislav, 2021-01-27 22:34:11

How to asynchronously change data in data in Vue?

When switching to the route, I get an error, since the data does not have time to load, tell me how to solve the problem?

In App.vue I load data into state:

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


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


Mutation:
initProducts(state, products) {
  state.products = products;
}


getter:
productDefaultSize: (state) => (code) => {
  const products = state.products;
  let product = null;

  for (let key in products) {
    product = products[key].find((item) => item.code === +code);

    if (product) {
      break;
    }
  }

  return product.meta[0];
}


Data of the route in which I need data:
data() {
  return {
    counter: 1,
    picked: null,
    loading: true,
  };
}


I'm trying to get the data in the hook:
created() {
  this.picked = this.$store.getters.productDefaultSize(this.code);
  this.loading = false;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Barkowski, 2021-01-28
@TypeOFF

Try to move data receiving to mounted() using await. Show some preloader before loading data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question