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?
In Vuex, actions are functions that call mutations. Actions exist because mutations must be synchronous, whereas actions can be asynchronous. You can define actions by passing a POJO as the actions property to the Vuex store constructor as shown below. To "call" an action, you should use the Store#dispatch() function.
You can access getters in actions, because actions get context as the first argument. like this: actions: { action1: (context, payload) => { console. log(context. getters.
actions in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later. As you can see above, it is highly beneficial for actions to return a Promise .
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; }); },
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With