Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from vuex mutation? (id for newly created object)

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?

like image 837
Rudi Avatar asked Feb 23 '17 00:02

Rudi


People also ask

How do you call an action from mutation Vuex?

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.

How do you access getters in mutations Vuex?

You can access getters in actions, because actions get context as the first argument. like this: actions: { action1: (context, payload) => { console. log(context. getters.

Can Action return value Vuex?

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 .


1 Answers

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;     });   }, 
like image 139
Austio Avatar answered Sep 25 '22 12:09

Austio