Search code examples
javascriptvue.jsvuejs2vuexvuex-modules

Vuex store, why adding to array overwrites all values in store with last entry?


I am using vuex-typescript. This is one store module:

import { getStoreAccessors } from "vuex-typescript";
import Vue from "vue";
import store from "../../store";
import { ActionContext } from "vuex";
class State {
  history: Array<object>;
}

const state: State = {
  history: [],
};

export const history_ = {
  namespaced: true,
  getters: {

    history: (state: State) => {

      return state.history;
    },

  },
  mutations: {

    addToHistory (state: State, someob: any) {

      state.history.push(someob);

    },

    resetState: (s: State) => {
      const initial = state;
      Object.keys(initial).forEach(key => { s[key] = initial[key]; });
    },
  },

  actions: {
    addToHistory(context: ActionContext<State, any>, someob: any) {
      commitAddToHistory(store, someob);
    }

  }

const { commit, read, dispatch } =
  getStoreAccessors<State, any>("history_");
const mutations = history_.mutations;
const getters = history_.getters;
const actions = history_.actions;

export const commitResetState = commit(mutations.resetState);
export const commitAddToHistory = commit(mutations.addToHistory);
export const getHistory = read(getters.history);
export const dispatchAddToSearchHistory = dispatch(actions.addToHistory);

Now if if call dispatchAddToSearchHistory or commitAddToHistory it is always the same all values get overwritten. For example if I add one element to store then it looks like this:

store = [
  {
    a: 1
  }
]

now when I add another object {b: 2} store becomes

store = [
  {
    b: 2
  },
  {
    b: 2
  }
]

All values are owerwritten by last entry. For example if I try to add {c:3} then store looks like (and so on):

store = [
  {
    c: 3
  },
  {
    c: 3
  },
  {
    c: 3
  }
]

Solution

  • ....hmmmm, well, I think you may be sending the same object, every time

    please try this mutation

    addToHistory (state: State, someob: any) {
      state.history.push({...someob});
    },
    

    or this action

    addToHistory(context: ActionContext<State, any>, someob: any) {
      commitAddToHistory(store, {...someob});
    }
    

    this, using the spread operator, clones the object. That way every item you add will be new object.