Search code examples
vue.jsvuex

Nuxt Store - Can´t get all values in commit


In Vuex i try to send some values to a store, like this.

 getStorage(
        { commit },
        name: String | undefined = undefined,
        objectA: ObjectA | undefined = undefined,
        objectB: ObjectB | undefined = undefined
    ) {
        if (selectedItinerary) {
            commit('setA', objectA, objectB)
        } else if (name) {
            commit('setB', name)
        }
    },

The problem: Only get name value, objectA and objectB return undefinied.

So: Somebody say what's wrong? Maybe can only send one param?

UPDATE 1

Calling dispatch

this.$store.dispatch('business/getLocalStorage', {
     name: this.name,
})

Store

getLocalStorage({ commit }, item) {
    if (item.name) {
        commit('setLocalStorageItinerary', item.name)
    }
}

setLocalStorageItinerary(state, { name }: { name: string }) {
    if (name) {
        const itinerary = new LocalStorage()
        itinerary.name = name
        state.itinerary = itinerary
    }
},

Solution

  • Assuming getStorage is an action, which receive the Vuex context as the first argument and a payload as the second, just wrap your values up inside an object before passing it as the payload.

    eg.

    somewhere in your app...
    
    let payload = {
      name: someValue,
      objectA: someObject,
      objectB: someOtherObject
    }
    
    this.$store.dispatch('getStorage', payload)
    
    actions.js
    
    getStorage({ commit }, payload) {
      if (selectedItinerary) {
        commit('setA', payload.objectA, payload.objectB)
      } else if (payload.name) {
        commit('setB', payload.name)
      }
    }
    

    It isn't clear from your example where selectedItinerary is defined, but I think you get the gist from the above.