Accessing getters within Vuex mutations - vue.js

Within a Vuex store mutation, is it possible to access a getter? Consider the below example.
new Vuex.Store({
state: {
question: 'Is it possible to access getters within a Vuex mutation?'
},
mutations: {
askQuestion(state) {
// TODO: Get question from getter here
let question = '';
if (question) {
// ...
}
}
},
getters: {
getQuestion: (state) => {
return state.question;
}
}
});
Of course the example doesn't make much sense, because I could just access the question property directly on the state object within the mutation, but I hope you see what I am trying to do. That is, conditionally manipulating state.
Within the mutation, this is undefined and the state parameter gives access to the state object, and not the rest of the store.
The documentation on mutations doesn't mention anything about doing this.
My guess would be that it's not possible, unless I missed something? I guess the alternative would be to either perform this logic outside of the store (resulting in code duplication) or implementing an action that does this, because actions have access to the entire store context. I'm pretty sure that it's a better approach, that is to keep the mutation focused on what it's actually supposed to do; mutate the state. That's probably what I'll end up doing, but I'm just curious if accessing a getter within a mutation is even possible?

Vuex store mutation methods do not provide direct access to getters.
This is probably bad practice*, but you could pass a reference to getters when committing a mutation like so:
actions: {
fooAction({commit, getters}, data) {
commit('FOO_MUTATION', {data, getters})
}
},
mutations: {
FOO_MUTATION(state, {data, getters}) {
console.log(getters);
}
}
* It is best practice to keep mutations a simple as possible, only directly affecting the Vuex state. This makes it easier to reason about state changes without having to think about any side effects. Now, if you follow best practices for vuex getters, they should not have any side effects in the first place. But, any logic that needs to reference getters can run in an action, which has read access to getters and state. Then the output of that logic can be passed to the mutation. So, you can pass the reference to the getters object to the mutation, but there's no need to and it muddies the waters.

If you put your getters and mutations in separate modules you can import the getters in the mutations and then do this:
import getters from './getters'
askQuestion(state) {
const question = getters.getQuestion(state)
// etc
}

If anyone is looking for a simple solution, #bbugh wrote out a way to work around this here by just having both the mutations and getters use the same function:
function is_product_in_cart (state, product) {
return state.cart.products.indexOf(product) > -1
}
export default {
mutations: {
add_product_to_cart: function (state, product) {
if (is_product_in_cart(state, product)) {
return
}
state.cart.products.push(product)
}
},
getters: {
is_product_in_cart: (state) => (product) => is_product_in_cart(state, product)
}
}

You also can reference the Store object within a mutation, if you declare the store as an expression, like this:
const Store = new Vuex.Store({
state: {...},
getters: {...},
mutations: {
myMutation(state, payload) {
//use the getter
Store.getters.getter
}
}
});

Vuex 4
const state = () => ({
some_state: 1
})
const getters = {
some_getter: state => state.some_state + 1
}
const mutations = {
GET_GETTER(state){
return getters.some_getter(state)
}
}
Somewhere in you component
store.commit('GET_GETTER') // output: 2

Another solution is to import the existing store. Assuming you're using modules and your module is called foo, your mutator file would look like this store/foo/mutations.js:
import index from '../index'
export const askQuestion = (state, obj) => {
let store = index()
let getQuestion = store.getters['foo/getQuestion']
}
I'm not saying this is best practise but it seems to work.

At least in Vuex 3/4, I've reached for this pattern numerous times: simply use this.getters.
Inside a mutation, regardless if you are inside a Vuex module or not, this is always reference to your root store.
So:
mutations: {
doSomething(state, payload) {
if (this.getters.someGetter) // `this.getters` will access you root store getters
}
Just to be extra clear, this will work if the getter you're trying to access belongs to your root store OR to any other non-namespaced module, since they are all added (flattened) to this.getters.
If you need access to a getter that belongs to any namespaced Vuex module, just remember they are all added to the root store getters as well, you just have to use the correct key to get to them:
this.getters['MyModuleName/nameOfGetter']
The great thing about this is that it also allows you to invoke mutations that belong either to the root store or any other store. this.commit will work exactly as expected as well Source

Related

Vuex 4 + Vue 3 using shared state actions in modules

I have a Vue 3 app (without TypeScript), and I'm using a Vuex 4 store.
I have my store separated into modules that represent some common themes, for example I have a user module that contains the store, getters, actions etc that are appropriate for dealing with a user. But, I also have some common functionalities that is present in all of my modules, and it's an obvious place where I could simplify my modules and thin them out a bit.
Let's say for example that I have a generic set() mutator, like below:
const mutations = {
set(state, payload) {
state[payload.key] = payload.data;
}
}
This will simply take in a payload and populate whatever store object the payload 'key' field belongs to, and it works well when I want to simply set a single field in my store. Now, the issue is that this set() function is being duplicated in every single store module that I have since it's just a generic store mutation, and once the number of modules I reach increases a bit, you can imagine that it's quite wasteful and pointless to include this mutation every single time.
I'm not sure how to implement this, however.
My current main store file looks like this (simplified for the sake of the question):
// store/index.js
import { createStore } from "vuex";
import module1 from "./modules/module1";
import module2 from "./modules/module2";
export const store = createStore({
modules: { module1, module2 },
});
All of my modules are implemented in the same exact way:
// store/modules/module1.js
const state = { };
const mutations = { set(state, payload) };
const actions = { };
const getters = { };
export default {
namespaced: true,
state,
getters,
actions,
mutations
};
And then somewhere in a component or wherever I'd call the specific module action/mutation/store I need with the below:
...mapMutations: ({ set: "module1/set" })
What would be the best way for me to bring that shared functionality out into a singular place, and how would I properly use it if I, for example, wanted to set and mutate the store in module1 and module2 at the same time properly? The part that I'm not sure about is how exactly I could call a generic mutation and have it target the desired module's state
Thanks to this answer linked by #Beyers, I've implemented the store in a similar fashion to this:
// store/sharedModuleMethods.js
export default class {
constructor() {
this.mutations = {
set(state, payload) {}
}
}
}
And then in the modules, I just instantiate the class and spread the methods where they need to be
// store/modules/module1.js
import SharedModuleMethods from "../sharedModuleMethods";
const methods = new SharedModuleMethods()
const mutations = {
...methods.mutations,
// Module specific mutations go here
};
And then in whatever component I need to set() something, I can just call the mutation like I would before
...mapMutations: ({ setModule1: "module1/set", setModule2: "module2/set" })
It's not quite as automated and streamlined as I'd personally prefer (define it once, have the modules magically have all the methods available to them via a flag or something), but alas life isn't perfect either.

sub-property write commit withing store actions using vuex-pathify make.mutations

Here is how my store looks like:
const state = {
user: {
profile: {
phoneNumber: '',
}
}
}
const mutations = make.mutations(state)
const actions = {
submitPhoneNumber({commit}, phone_number) {
// blah blah
commit('SET_USER#profile.phoneNumber', phone_number);
}
}
But no such mutation can be found.
Maybe I could import store.js within store.js and use the set helper but I believe things can get pretty creepy specially because of the (In my opinion poor) design decision that the library creator has made to combine commit and dispatch (I believe being explicit would have been much better here)
Pathify author here.
You can't commit a mutation with sub-property syntax using Vuex mutations, because Vuex will treat it as a string.
You are correct that you would need to use store.set() to do this.
You can be explicit with commits and dispatches by appending a ! to the call. This is called "direct syntax":
https://davestewart.github.io/vuex-pathify/#/api/paths?id=direct-syntax
To commit directly using the sub-property syntax, use the Payload class:
https://github.com/davestewart/vuex-pathify/blob/master/src/classes/Payload.js
https://davestewart.github.io/vuex-pathify/#/api/properties?id=payload-class
Something like this should work:
import { Payload } from 'vuex-pathify'
commit('SET_USER', new Payload('SET_USER', #profile.phoneNumber', phone_number);
Looks like I haven't documented this, so I have a made a ticket here:
https://github.com/davestewart/vuex-pathify/issues/80
It's using a commit from a component, but should work just the same.
People have asked before if it would be possible to use Pathify-style commits in actions and I said it wasn't, but I've just thought of something that might make it possible.
Follow this feature request for more info:
https://github.com/davestewart/vuex-pathify/issues/79

Correct usage of getters in vuex

I'm currently developing an app with vue v2, and something got me thinking. It's kind of hard to find information for good practices so I decided I will ask here.
I have a laravel api and vue for front end. Until now my models were such that will hold only a few objects (< 100), so I just put the in the state, and get what ever needed with a getter. Now I have a model that will hold > 10000 objects, so putting them all into the state is pretty much out the topic. The way I solve this problem is a have with action that gets a single object from the api by id, and put it in the state, after a check if its not in there already. The check happens with a getter that I'm also using when I need this object. So I have similar structure:
​
// mutation
[mutation_types.FETCH_SOMETHING](state, {something}) {
if (!this.getters.getSomethingById(something.id)) {
state.somethings.push(something)
}
}
// action
const {data} = await axios.get('~route~')
commit(mutation_types.FETCH_SOMETHING, {something: data.something})
// getter
getSomethingById: state => id => {
return state.somethings.find(something => something.id === id)
}
​
So this is working, but there are 2 problems that I see. The first is every time when I need a something I should call the dispatch to get the item from the api into the state and then the getter to get the actual object and the second problem is the check is happening after the api call, so even if I have this specific something in the state, I'm doing a request for it.
A way to fix both of those problems that I though of calling the just working with the getter, which will check that state, if the searched ID is found in there it will be returned, if not, the dispatch will get it from the api and then return it.
I feel like I'm adding logic to the getter that doesn't belong there, but I can't think of another way to achieve this. Is there something that I'm missing / doing wrong somewhere?
Take advantage of the async nature of vuex actions and promises. Do the check for existence directly in the action along with the api call if needed:
state: {
items: []
}
mutations: {
addItem: (state, item) => {
state.items.push(item)
}
}
actions: {
fetchItem: async (context, id) => {
let item = context.state.items.find(i => i.id === id)
if (!item) {
item = await axios.get('/example/' + id).then(response => {
context.state.commit('addItem', response.data)
return response.data
})
}
return item
}
}

Modify the store example to protect state

Vue gives this example of a simple store, where state is modified by calling an action on the store...
var store = {
debug: true,
state: {
message: 'Hello!'
},
setMessageAction (newValue) {
if (this.debug) console.log('setMessageAction triggered with', newValue)
this.state.message = newValue
},
clearMessageAction () {
if (this.debug) console.log('clearMessageAction triggered')
this.state.message = ''
}
}
But state is a public property of store, and no-one is obliged to pass by setMessageAction() to modify it. Is there a simple trick to protect state, but still have it observed by vue? I can't think of one.
JavaScript does not support access modifiers; everything is public.
There are various ways of encapsulating private implementation details in JavaScript, but in your example the store's state needs to be public so that it can be assigned to the component's data.
Vuex has a strict mode which, if enabled, will throw an error if the state is modified outside of mutation handlers.

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?
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;
});
},
Disclaimer : I don't know if it is truely a good idea, but at least, it seems to work, and to me, it feels prettier than having to use actions and promises, or to generate the id in the action...
With your mutation, you can pass an argument. To return a value from a mutation (like a newly created id), I write it to a placeholder in that argument :
someMutation(state, arg){
//...
arg.out = {
status : "succeed"
}
}
//...
this.$store.commit('someMutation', arg);
if(arg.out !== "succeed") console.log("ERROR");