Search code examples
javascriptvue.jsstatevuexmutation

more data passed in state, it is not taken correctly


I have ready-made constants that I need to save in the state:

 const day = "25/02/2020";
 const timeStart = "08:00";
 const timeEnd = "00:00";

inside my file for vuex I have this:

  export default new Vuex.Store ({
    state: {
       dateSelected: [], // selected date
    },
    mutations: {
      saveDateSelected (state, [newDateSelected, newTimeStart, newTimeEnd]) {
         const newobject = {
            DateStart: newDateSelected + "-" + newTimeStart,
            DateEnd: newDateSelected + "-" + newTimeEnd,
         };

         state.dateSelected.push (newobject);
      }
    },

when in my component I go to recall the data with:

    this.saveDateSelected (day, timeStart, timeEnd);

if I do a "console.log (this.dateSelected);" gives me as a result:

   DateEnd: "2 - /"
   DateStart: "2 - 5"

when it should give me:

  DateEnd: "25/02/2020 - 00:00"
  DateStart: "25/02/2020 - 08:00"

Solution

  • You should not directly call store mutation methods from a component. Do commits instead this.$store.commit('saveDateSelected, [day, timeStart, timeEnd])

    Also make sure that you properly access vuex store in a component via computed property of the component.