Search code examples
javascriptvue.jsaxiosvuex

How delete an item using vuex?


I just started learning vuex and can`t delete item. I can delete item directly in the component.

deleteCar (cars, id) {
        this.$http.delete('http://localhost:3000/cars/' + cars.id)
          .then(() => {              
              this.cars.splice(id, 1)
          })
      }

In vuex i have:

state: {
    car: {},
    cars: []
  },
  mutations: {
    ADD_CAR (state, car) {
      state.car = car
    },
    GET_CARS (state, cars) {
      state.cars = cars
    }

  },
  actions: {
    createCar({commit}, car) {
      axios.post('http://localhost:3000/cars', car)
        .then(() => {
          commit('ADD_CAR', car)
        })
    },

    loadCars({commit}) {
      axios.get('http://localhost:3000/cars')
        .then(res => {
            const cars = res.data
            commit('GET_CARS', cars)
        })
    }
  }

Code in component where i wanna delete item:

<div class="card mb-3" v-for="(car, i) in cars" :key="i">
      <div class="card-header">
      Cars name: {{ car.carName }}
      </div>
      <div class="card-body">
        <h5 class="card-title">Country: {{ car.country }}</h5>
        <p class="card-text">Year of manufacture: {{ car.carYear }}</p>
        <button class="btn btn-primary mb-5" @click="deleteCar(car, i)">Delete Car</button>
      </div>
    </div>

I can add car and get cars. But can`t delete


Solution

  • You want to commit a mutation to delete the car

    Here is your method

    deleteCar (cars, id) {
        this.$http.delete('http://localhost:3000/cars/' + cars.id)
            .then(() => {              
                  this.cars.splice(id, 1);
            });
    }
    

    Instead of deleteCar(cars, id) you will want to change it to deleteCars({commit}, id)

    So your action would be

    deleteCar ({commit}, id) {
        this.$http.delete('http://localhost:3000/cars/' + id)
            .then(() => {              
                 commit('DELETE_CAR', id);
            });
    }
    

    And you have a mutation DELETE_CAR

    DELETE_CAR(state, id){
        index = state.cars.findIndex(car => car.id == id);
        state.cars.splice(index, 1);
    }