[Vuejs]-How to populate form from store state data returned from vuex with getters?

0👍

It’s a little difficult to give a concrete answer without seeing the store code but you’re going to have to wait until the store has finished fetching the data before trying to read it into your form.

Probably the easiest way is to use the Promise returned by fetchIncomeTaxRate. All actions return a Promise when called, even if you don’t return one yourself. Make sure you’re returning a suitable Promise, i.e. one that doesn’t resolve until the data is loaded. If you’re loading the data using a library such as axios that supports Promises then this should be very easy, you just need to return the Promise it returns to you.

Once you’ve returned a suitable Promise you can do something like this:

this.fetchIncomeTaxRate(this.id).then(() => {
    this.record.min_salary = this.getIncomeTaxRate.min_salary;
    // ... others here
});

You may want to put in extra code to prevent the form being seen/edited until the relevant data is populated.

An alternative to using Promises would be to use watch to wait for getIncomeTaxRate to change. However it would be difficult to ensure that you only react to exactly the right change.

Update:

Now that you’ve posted your store code I’ve tried running your code myself (as close as I could get) and record was updated fine if I used then in the way I outlined above. Most likely this suggests that there’s another problem that isn’t in the code you’ve posted. For example, it might be that the data returned from the server isn’t in exactly the format you’re expecting.

To diagnose further I suggest putting in some console logging. I’d put some in at the top of the then for starters:

this.fetchIncomeTaxRate(this.id).then(() => {
    console.log('in then', this.getIncomeTaxRate, this.getIncomeTaxRate.min_salary);

    this.record.min_salary = this.getIncomeTaxRate.min_salary;
    // ... others here
});

I’d also put some in fetchIncomeTaxRate too:

async fetchIncomeTaxRate({ commit }, id) {
  console.log('called fetchIncomeTaxRate');

  const response = await axios.get(
    commonAPI.PAYROLL_BASE_URL + `/income-tax-rates/${id}`
  );
  commit("setIncomeTaxRate", response.data);

  console.log('committed', response.data);
}

Not only should the logged values be correct but the order of the log messages is important too. The data should be committed before the then is called.

Leave a comment