Why updating object in array is not working in VUE?

Viewed 86

I'm trying to make an update and I managed to do it in the firebase, but in the store is not updating. Here is my code

editCar() {
      let result = this.balmUI.validate(this.formData);
      let { valid, message } = result;
      this.message = message;
      console.log(`Vrei sa editezi masina: ${this.formData.vehicle}`);
      console.log(utils.url);

      if (valid) {
        let data = {
          vehicle: this.formData.vehicle,
          color: this.formData.color,
          fuel: this.formData.fuel,
          status: this.formData.status,
          price: this.formData.price,
        };

        let requestParameters = { ...utils.globalRequestParameters };
        let token = window.localStorage.getItem("token");
        requestParameters.headers.Authorization = "Bearer " + token;
        requestParameters.method = "PUT";
        requestParameters.body = JSON.stringify(data);

        fetch(utils.url + "cars/" + this.formData.id, requestParameters)
          .then((res) => res.json())
          .then((res) => {
            console.log(res.message);
            if (
              res.message === "Decoding error!" ||
              res.message === "Your token expired!"
            ) {
              console.log("nu ai voie!");
            } else {
              data.id = res.id;
              this.$store.dispatch("editCar", data);
              this.$router.push("/");
            }
          });
      }

This is the index from store, which contais my mutation and action. Anything else is working properly

import { createStore } from 'vuex'

export default createStore({
  state: {
    cars: [],
    isAuthentif: false
  },
  getters: {
    cars: state => {
      return state.cars
    }
  },
  mutations: {
    SET_AUTH: (state, status) => {
      state.isAuthentif = status
    },
    SET_CARS: (state, cars) => {
      state.cars = cars
    },
    ADD_CAR: (state, car) => {
      state.cars.push(car)
    },
    DELETE_CAR: (state, id) => {
      var index = state.cars.findIndex(car => car.id == id)
      state.cars.splice(index, 1);
    },
    EDIT_CAR: (state, car) => {
      state.cars.forEach(c => {
        if(c.id === car.id) {
          c = car;
        }
      })
    }
  },
  actions: {
    login: ({ commit }, payload) => {
      commit('SET_AUTH', payload)
    },
    fetchCars: ({ commit }, payload) => {
      commit('SET_CARS', payload)
    },
    addCar: ({ commit }, payload) => {
      commit('ADD_CAR', payload)
    },
    deleteCar: ({ commit }, payload) => {
      commit('DELETE_CAR', payload)
    },
    editCar: ({ commit }, payload) => {
      commit('EDIT_CAR', payload)
    }
  },
  modules: {
  }
})

EDIT_CAR is the problem, I think. What is wrong? Why it is not updating on the screen. I've also tried to use this https://vuex.vuejs.org/guide/mutations.html#object-style-commit like this c = {...c, car} but is not working

2 Answers

Can you try to change your EDIT_CAR mutation to:

const index = state.cars.findIndex(x => x.id === car.id)
state.cars.splice(index, 1, car)

If you haven't done already, place a console.log(car) at the beginning of the mutation so you make sure it gets called and the car payload is what you expect.

Your problem is not in the mutation. The problem is in your editCar() in here this.$store.dispatch("editCar", data); You put data, and with vehicle, color, fuel, status and price and then in your mutation you verify ID. You didn't pass any id. You cand make a new object if you don't want you id, like this:

editCar() {
      let result = this.balmUI.validate(this.formData);
      let { valid, message } = result;
      this.message = message;
      console.log(`Vrei sa editezi masina: ${this.formData.vehicle}`);
      console.log(utils.url);

      if (valid) {
        let data = {
          vehicle: this.formData.vehicle,
          color: this.formData.color,
          fuel: this.formData.fuel,
          status: this.formData.status,
          price: this.formData.price,
        };

        let requestParameters = { ...utils.globalRequestParameters };
        let token = window.localStorage.getItem("token");
        requestParameters.headers.Authorization = "Bearer " + token;
        requestParameters.method = "PUT";
        requestParameters.body = JSON.stringify(data);

        fetch(utils.url + "cars/" + this.formData.id, requestParameters)
          .then((res) => res.json())
          .then((res) => {
            console.log(res.message);
            if (
              res.message === "Decoding error!" ||
              res.message === "Your token expired!"
            ) {
              console.log("nu ai voie!");
            } else {
              let newData = {
                id: this.formData.id,
                vehicle: data.vehicle,
                color: data.color,
                fuel: data.fuel,
                status: data.status,
                price: data.price,
              };
              this.$store.dispatch("editCar", newData);
              this.$router.push("/");
            }
          });
      }
    },

Also in your mutation cand make something like this:

EDIT_CAR: (state, car) => {
      Object.assign(state.cars[state.cars.findIndex(c => c.id === car.id)], car);
    }
Related