2

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

4
  • What is state.cars? Is it an array of primitives, or an array of objects? Commented Nov 20, 2021 at 21:02
  • Array of objects @Terry Commented Nov 20, 2021 at 21:03
  • Is it possible to share a minimal reproducible example instead? Commented Nov 20, 2021 at 21:04
  • My object from array list is updated in the database, but not is the app page. In the app page is updated after manual refresh @Terry Commented Nov 20, 2021 at 22:48

2 Answers 2

1

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

In console log is the payload car I expect, but in my list the value is not changed :/
Maybe the problem is not from the mutation. Maybe it is the way I make this update. I have a list of cars and when I click the edit button of one car, I redirect to another router where I have a form in which I transfer a parameter with my car, and then I came back to my list which is not changed
Update, the problem is in the mutation. My state.cars is not changed and I dont understant why. Also, your answer is not good because it adds me another car in my list instead of replacing it
Well no that replaces the object it doesn't add one. And it's better than using Object.assign. If id was not set in payload means data.id = res.id was the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.