Search code examples
vue.jsvuexvuex-modules

How to fetch and reset modules in Vuex


I got 2 modules #module A

const state = {
    a: '',
    b: '',
    c: '',
}
const mutations = {
    reset(state) {
    state.a = ''
    state.b = ''
    state.c = ''
  }
}

I use vuex-map-fields to enable two-way-binding in componentA

After that I want to fetch all states of module A to module B (state.items), and RESET after done fetching #module B

const state = {
 items: []
},
const mutations = {
    addItem (state) {
        state.items.push(moduleA.state)
    },
}

I tried

dispatch('moduleB/addItems')
commit('molduleA/reset')

with data of moduleA

const state = {
    a: '1',
    b: '2',
    c: '3',
}

but it's not working, only store reset state of moduleA

#resultOfModuleB

const state = {
 items: [
    {a:'', b:'', c:''}
 ]
},

If I only dispatch(‘moduleB/addItems’), it's working

const state = {
 items: [
    {a:'1', b:'2', c:'3'}
 ]
},

What is the best way to do? Thanks in advance


Solution

  • Okay so I think I understand your problem now. Correct me if I'm wrong! If you just call the ModuleB function, then B is containing the data of A.state as it should. But if you call the reset function on A.state both are empty.

    The reason for this could be because of the way you add the A.state object to your B.state. By pushing the A.state object into the B.state.items array you are not coping the object or its values. You just pass the address where the object is located in the memory.

    So A.state and the element of the B.state.items array are "looking" at the same location in the memory. If you now rest A.state, therefore the B.state.items array element is also changed.

    You can try to fix this with a deepCopy of the state array. There are functions like cloneDeep in lodash or similar to do so. But to understand fully what is going on you can write such a function your self because its not that hard.

    function deepCopy(obj) {
      const retObj = {}
      Object.keys(obj).forEach(prop => {
        retObj[prop] = obj[prop];
      });
    
      return retObj
    }
    

    This function should work with objects like yours and in your case. (If your objects have nested properties it wont work because of the way its accessing the properties)

    I hope I didnt miss anything and could help you somehow!