Search code examples
vue.jsvuex

How to pass values from state in vuex post request


I am collecting data using get and set for my form. I want to post the states to the api. How can I move the states or group them somehow so I can pass them as to action?

  state: {
    firstname: "",
    lastname: "",

  },
  mutations: {
    setFirstName(state, value) {
      state.firstname = value
    },
    setLastName(state, value) {
      state.lastname = value
    },

So it looks like this:

sendInfo({commit}, object) {
axios.post('API_URL', object)
.then((response) => {
 ...
})

}
computed: {
            firstname: {
                get() {
                    return this.$store.state.firstname
                },
                set(value) {
                    this.$store.commit("setFirstName", value)
                }
            },

or am I approaching this wrongly?


Solution

  • It's probably best to put these values inside a state object like:

    state: {
      user: {
        firstname: '',
        lastname: ''
      }
    }
    

    You can set the object in an action

    actions: {
      setData({ commit }, payload) {
        commit('SET_DATA', payload);
      }
    },
    mutations: {
      SET_DATA(state, payload) {
        state.user = payload;
      }
    }
    

    It also makes it concise when using mapState:

    computed: {
       ...mapState(['user'])
    }