Search code examples
vue.jsvuex

Accessing vuex data by a known id


I have created a vuex store and stored several rows of data that i fetched from a remote source. The data is actually rows from a mysql table.

The data is in this format

[{
    "id": "1",
    "property_country": "usa",
    "property_name": "i and m towers",
    "property_stars": "4",
    "property_city": "austin",
    "property_region": "texas",
    "property_type": "serviced partment",
    "date_created": "3563763673",
    "date_updated": "33377363",
    "the_user_id": "1"
}, {
    "id": "2",
    "property_country": "uk",
    "property_name": "eagle towers",
    "property_stars": "5",
    "property_city": "kampala",
    "property_region": "kampala",
    "property_type": "motel",
    "date_created": "3563763673",
    "date_updated": "33377363",
    "the_user_id": "1"
},

I want to be able to access vuex data by id, remove by id, update by id

So far i can access console.log(this.$store.state.properties[1].property_country);

like that. I know the id from looping the data and so, i want to be able to use the known id to perform some mutations. What is the way to view how the data in vuex is stored and how can i access any data stored in vuex if i know the id of the row?


Solution

  • 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: {...}})