Vue.js – Return value from vuex mutation? (id for newly created object)

vue.jsvuejs2vuex

I'm trying to create an object in one part of vuex store, and then pass id to it to another object, and i'm not sure how to properly do that since mutations can't return returning anything (in this case, id).

Two store objects look like this:

// store/report.js
const state = {
    name: 'Untitled Report',
    subReportIds: []
};

// store/subReport.js
const state = { ... }

And i'd like this action to create blank report, then blank subreport, and then assign subreport id to newly created report. (subreports are independent entities, and can be used by multiple reports, hence different area in store)

const actions = {
    createNewReport({ state, commit }) {
        commit(mutationTypes.CREATE_NEW_REPORT)
        // below doesn't work - i can't get return from mutation
        let newSubreportId = commit(mutationTypes.ADD_NEW_SUBREPORT)
        // if this worked, i'd then do something like
        commit(mutationTypes.ADD_SUBREPORT_TO_REPORT, newSubreportId)
    }
};

How can i achieve the above?

Best Answer

So best way to accomplish to me would be to dispatch actions instead of committing the mutations. If you look at the methods in Vuex source, commit only executes with no return (so is a void) and dispatch returns the value you return from the action (which is a function)

For my actions, i always return a promise so that i can compose them like you mention above. Here is an example.

fetchSomething ({ commit }) {
  return mockApiGetIds()
    .then(response => {
      commit({
        type: SOME_MUTATION,
        ids: response
      });
    
      return response;
    });
  },