Search code examples
javascripttypescriptvue.jsvuejs2vuex

VUEX Getter = Filter array inside array


I have a getter in VUEX and i'm trying to filter an array inside an array but keep getting a warning about modifying state inside the getter.

Error: [vuex] do not mutate vuex store state outside mutation handlers

I know i can do a simple filter on the top level array but it doesn't seem to work on the people array, the only way that i can get it to show the results i want is by doing the following (which is wrong)

for (const company of company.companies) {
      const filteredPeople: IPerson[] = company.people.filter(
        x => x.jobId === 1
      );
      company.people = filteredPeople;
    }

Solution

  • In short, you cannot modify state inside getters as it would easily result in an endless loops. Besides, getters are not meant to ever modify any kind of outer state, but rather just return (perhaps translated) piece of state for further data presentation. Try this piece of code, instead of modifying state you are returning translated copies of companies with filtered people:

    return company.companies.map(c => ({...c, people: c.people.filter(p => p.jobId === 1)}))