Home > Software design >  Search in vuejs with computed status
Search in vuejs with computed status

Time:11-25

I have a component that render data from a store in vuex

the component has a computed status when a search query has been written it will filter that store state which is kommunhanteringItems to search for a customer and here i have a problem which is the computed status will mutate the state in the store which i do not want it to do that.

State in the store which is this.$store.state.todos.kommunhanteringItems:

kommunhanteringItems: [
  {
    gId: 1,
    gtitle: 'Group1',
    items: [
      {cid: 1, customer: 'Vicotria Nils'},
      {cid: 2, customer: 'Mona Andersson'}
    ]
  },
  {
    gId: 2,
    gtitle: 'Group2',
    items: [
      {cid: 3, customer: 'Jacob Ström'},
      {cid: 4, customer: 'Magdalin eriksson'}
    ]
  }
]

Component computed:

SearchInTables() {
  let k = this.$store.state.todos.kommunhanteringItems
  if (this.SearchQuery != '') {
    let SearchFilter = []
    let self = this
    k.forEach(function (x) {
      let items = x.items
      let filter = items.filter((item) => {
        return item.customer.toUpperCase().includes(self.SearchQuery.toUpperCase())
      })
      x.items = filter
      SearchFilter.push(x)
    })
    return SearchFilter
  } else {
    return k
  }
},

CodePudding user response:

The problem is that you are writing to x which is an object in an array in the store, when you do x.items = filter.

To avoid this, you need to create a copy of x, and replace items. See below for an example of doing this with Object.assign

SearchInTables() {
  let k = this.$store.state.todos.kommunhanteringItems
  if (this.SearchQuery != '') {
    let SearchFilter = []
    let self = this
    k.forEach(function (x) {
      let filter = x.items.filter((item) => {
        return item.customer.toUpperCase().includes(self.SearchQuery.toUpperCase())
      })
      SearchFilter.push(Object.assign({}, x, { items: filter })
    })
    return SearchFilter
  } else {
    return k
  }
}
  • Related