Sensanaty
Sensanaty

Reputation: 1096

Vuex mutating stored key values for one specific object

I have an employees Object, which itself is an array of Objects, in my Vuex (Nuxt) store. One of the keys stored inside the employees object is total_reviews. The original data is obtained through an API I maintain, including the total_reviews which is calculated serverside.

I've recently introduced some filtering functionality into the app, and it's created a problem for the total_reviews. My users can have multiple venues as well as multiple employees, and since my usual clients are restaurant chains, some of the employees might be working in multiple venues. As such, when a client filters by their venues, what currently happens is that the total_reviews value doesn't actually change to accurately reflect how many reviews an Employee might've gotten in any one specific venue, or a combination of various venues. As such, I've included an extra key that I get from my API, which is the number of reviews an employee has gotten per Venue, the idea being that I can just look at which venues the client chooses to filter by, then sum it up and show that number.

My question is, is it possible for me to set up a mutation where I modify the value of employee.total_reviews? I'm not too familiar with Vuex, so the whole mutation thing is a bit confusing to me, but I can't figure out how to find the specific employee in a loop and update just their own stored total_reviews key.

Presume for the sake of simplicity that I'd want to set an arbitrary employee's total_reviews value to be 10, how would I go about doing that in Vuex?

Upvotes: 0

Views: 503

Answers (1)

Mike
Mike

Reputation: 805

It seems you may have more of a data architecture issue here than just the question of mutating the store. It's hard to say without more knowledge of your implementation, but this seems like something that would be handled better using Props than the store.

Here is a rough idea of you might set up your store and run the mutation:

Vuex Store:

Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    employees: []
  },
  mutations: {
    updateEmployeeTotalReviews(state, data) {
      const index = state.employees.findIndex((e) => e.id === data.employeeId);
      state.employees[index]['totalReviews'] = data.reviewsCount;
    }
  }
})

And in a component:

updateTotalReviews(employeeId, reviewsCount) {
  const data = {
    employeeId: employeeId,
    reviewsCount: reviewsCount
  };
  this.$store.commit('updateEmployeeTotalReviews', data);
}

Upvotes: 1

Related Questions