Search code examples
vue.jsvuex

Vuex - local variable assigned a mapState value, changing local variable also changes store variable?


Why does my original Vuex object get changed when I assign its value to a local variable and manipulate the local value? I can post my store.js if necessary.

I have something like this:

  data() {
    return {
      localObject: [],
    };
  },
computed: mapState(["storeObject"]), // main store object
  created() {
    this.localObject = this.storeObject;
    this.prepareData();
  },
methods: {
    prepareData() {
      this.localObject.forEach((event, i) => {
        delete event.artist_supporting;
        delete event.genre;
      });
      // console.log(this.storeObject); // why is this object getting changed by the localObject.forEach? 
    }
}

Here's the complete computed() block. If I console this.eventsData at the top of the computed value calendarData() it's complete as expected. But if I console this.eventsData at the bottom, before the return, it's altered as if I was manipulating it directly.

computed: {
    ...mapState(["loading", "eventsData"]),
    calendarData() {
      console.log(this.eventsData); // correct "complete" object
      let data = this.eventsData;
      data.forEach((event, i) => {
        delete event.artist_supporting;
        delete event.genre;
        delete event.venue;
        delete event.venue_city;
        delete event.venue_state;
        delete event.capacity;
        delete event.announce_date;
        delete event.onsale_date;
        delete event.promoter;
        delete event.business_unit;
        delete event.show_type;
        delete event.confirm_date;
        delete event.cancelled_date;
        delete event.status;

        event.venue_id = `event_${i}`;
        event.id = event.venue_id;
        event.title = event.artist_headliner;
        event.startDate = event.event_date;

        delete event.venue_id;
        delete event.artist_headliner;
        delete event.event_date;

        let date = new Date(event.startDate);
        let day = date.getDate();
        let month = date.getMonth() + 1;
        let year = date.getFullYear();
        if (day < 10) {
          day = "0" + day;
        }
        if (month < 10) {
          month = "0" + month;
        }
        event.startDate = year + "-" + month + "-" + day;
      });
      console.log(this.eventsData); // edited object
      return data;
    },
  },

Solution

  • Because by doing this.localObject = this.storeObject; you are assigning the reference of storeObject to localObject which makes both variables point to the same memory. Mutating either of them will affect another. If you need to isolate the effect, you have to make a deep copy. The easiest way is to use JSON.parse(JSON.stringify(...):

    this.localObject = JSON.parse(JSON.stringify(this.storeObject))