[Vuejs]-Accessing vuex data by a known id

2๐Ÿ‘

โœ…

Get by Id:

this.$store.state.properties.find(property => property.id == 1).property_country

// OR

getById(id) {
  this.$store.state.properties.find(property => property.id == id)
}
getById(1).property_country // "usa"

Remove by id

removeById(id) {
  this.$store.state.properties.splice(this.$store.state.properties.findIndex(p=>p.id == id), 1)
}

Update by Id:

updateById(id, newObject) {
  this.$store.state.properties[this.$store.state.properties.findIndex(p=>p.id == id)] = JSON.parse(JSON.stringyfy(newObject))
}
// here you have to make some logic to make sure the id still makes sense.

Update a single property

this.$store.state.properties[this.$store.state.properties.findIndex(p=>p.id == 1)].property_country = "NEW_VALUE"

The Vuex way

// You can always get data from store using this.$store.state
// But to update, change or remove, you need mutations
mutations: {
  removeById(state, id) {
    state.properties.splice(state.properties.findIndex(p=>p.id == id), 1)
  },
  updateById(state, payload) { // payload = {id: 1, newObject = {..]}
    state.properties[state.properties.findIndex(p=>p.id == payload.id)] = JSON.parse(JSON.stringyfy(payload.newObject))
  }
}

// Use like this
this.$store.commit('removeById', 1)
this.$store.commit('updateById', {id: 1, newObject: {...}})
๐Ÿ‘คtauzN

1๐Ÿ‘

Try out a getter with method style access

getters: {
  // ...
  getPropById: (state) => (id) => {
    const {property_country}=state.properties.find(p=> p.id === id)
   
     return property_country;

  }
}

then use it like this.$store.getters.getPropById(1)

Leave a comment