How to send state data via POST request in Vuex?

Viewed 1270

Background: I have have a Vuex state object called 'expense' that is updated via form input fields in a 'form component'. I need to send that 'expense' object via POST

Problem: I set up an Action that makes the POST request. However the 'expense' object stored in the state is not being sent.

PS: The POST request is successful but the response proves that its not sending the data.

The response data:

enter image description here

Store State


const mainURI = "/api/budget";

const expenseObj = {
  expensesKey: "",
  expensesValue: null,
  subExpense: null,
};

export const store = new Vuex.Store({
  state: {
    earnings: null,
    expenses: [
      {
        expensesKey: "",
        expensesValue: null,
        subExpense: null,
      },
    ],
  },

Store Action

  actions: {
    addBudget({commit},{ expenses, earnings }) {
      axios
        .post(mainURI, {
          earnings: earnings,
          expenses: expenses,
        })
        .then((res) => {
          console.log(res.data);
            let newExpense = res.data;
           commit("SUBMIT_BUDGET", newExpense);
        });
    },
  },

Store Methods

  mutations: {
    SUBMIT_BUDGET: (state, payload) => state.newBudget.push(payload),
    UPDATE_EARNINGS: (state, earnings) => state.earnings = earnings;
    UPDATE_KEYS(state, payload) {
      Vue.set(
        state.expenses[payload.index],
        "expensesKey",
        payload.expenseKeyValue
      );
    },
    UPDATE_VALUE(state, payload) {
      Vue.set(
        state.expenses[payload.index],
        "expensesValue",
        payload.expenseValueValue
      );
    },
  },
});

The form componenet

computed:{
 earnings: {
      get() {
        return this.$store.state.earnings;
      },
      set(value) {
        this.$store.commit("UPDATE_EARNINGS", value);
      },
    },
},
 methods: {
    submitBudget() {
      this.$store.dispatch("addBudget");
      console.log("triggers");
    },
    updateKey(event, idx) {
      const val = {
        expenseKeyValue: event.target.value,
        index: idx,
      };
      this.$store.commit("UPDATE_KEYS", val);
    },
    updateValue(event, idx) {
      const val = {
        expenseValueValue: event.target.value,
        index: idx,
      };
      this.$store.commit("UPDATE_VALUE", val);
    },
  }
1 Answers

When you dispatch the addBudget action, there is no payload such as:

this.$store.dispatch('addBudget', objectPayload);

Maybe that's because you intend to use earnings and expenses from state. If so, you can remove the payload argument and access state from the action context:

actions: {
  addBudget({ state, commit }) {
    axios.post(mainURI, {
      earnings: state.earnings,
      expenses: state.expenses,
    })
    .then((res) => {
      console.log(res.data);
      let newExpense = res.data;
      commit("SUBMIT_BUDGET", newExpense);
    });
  },
},
Related