vuex base state is shared between modules - vue.js

I am using multiple vuex modules in nuxt store and I want to use the same base state in multiple modules like this:
// ~/utils/Sharedstore.js
export default {
state: {
byId: {},
allIds: [],
}
},
// ~store/entities/myEntity.js
import SharedStore from '~/utils/SharedStore';
export const state = () => ({ ...SharedStore.state });
But it doesn't work, whenever i mutate one state the state of all modules will be changed.
When I do this for all my modules it works:
// ~store/entities/myEntity.js
export const state = () => ({
byId: {},
allIds: [],
});
Problem is I would like to have the duplicated base states in one place (SharedStore.state). Why does it not work when importing and how can I fix it?

I found a fix:
export const state = () => JSON.parse(JSON.stringify(ModelStore.state));
Need to deep clone the object using JSON.parse(JSON.stringify(obj)) instead of spreading.
I guess the contents of byId and allIds still get used by reference when spreading?

Related

Vuex Namespaced Store Sets Both States

In my project I have a rather complex vuex store which saves values of filter inputs and converts them into filters I can use to later query the backend. I use those filters next to two different tables. If I filter for id = 123 in table1 I DO NOT want to have the filter in table2 to be id = 123. Thats why I created a module and try to use a namespaced store. My vuex store index.js looks something like this:
import myFilterModule from './filter.module';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
filter1: myFilterModule,
filter2: myFilterModule,
},
});
And my module looks like this:
const state = {
idFilter: null,
};
const actions = {};
const mutations = {
[SET_ID_FILTER](state, id) {
state.idFilter = id;
},
};
const getters = {
getFilter(state) {
return state.idFilter;
},
};
export default {
namespaced: true,
state: () => state,
actions,
mutations,
getters,
};
The problem is, if I commit a change on either of those namespaces like this:
this.$store.commit('filter1/' + SET_ID_FILTER, '123');
Both of these functions:
this.$store.state['filter1'].idFilter
this.$store.state['filter2'].idFilter
Return the same. Even tho I didnt even set. idFilter on filter2.
Am I using the namespaces wrong?
The problem is that a state is the same object in both module copies. If a module is supposed to be reused, initial state should be created with factory function:
const state = () => ({
idFilter: null,
});
...
export default {
namespaced: true,
state,
...
};
This is the reason why state is allowed to be a function.

In Nuxt, how to mutate a Vuex state in one module from the other?

I tried many things mentioned on the portal but nothing seems to work for me so posting here for some work-around.
I have 2 modules within my Nuxtjs application folder store\modules: ModuleA and ModuleB. For some verification in ModuleB I would like to access the state from ModuleA but for some reason, it's failing.
I tried rootScope, import etc but it did not work for me.
My state/modules/ModuleA.js:
export const state = () => ({
eventType: 'MyEvent',
})
export const mutations = {
eventTypePopulator (state, event) {
state.eventType = event
},
}
My state/modules/ModuleB.js:
export const state = () => ({
input: {}
})
export const mutations = {
jsonPreparation ({state, rootState}, payload) {
console.log(rootState.eventType)
// console.log($store.state.ModuleA.eventType)
}
}
I tried to import ModuleA into ModuleB and use it but that also did not work for me. Can someone please help me how can I access the state from one Module in another Module within Nuxtjs/Vuejs
As shown in the API reference, rootState is available in actions and getters.
It did not found any way of using it directly into a mutation.
Meanwhile, this can be achieved by passing it as a param to the mutation like this
ModuleB.js
const mutations = {
NICE_TASTY_MUTATION: (_state, { rootState, payload }) => {
// _state is not used here because it's moduleB's local state
rootState['moduleA'].eventType = payload
},
}
const actions = {
async myCoolAction({ commit, rootState }, { ...}) {
commit('NICE_TASTY_MUTATION', {
rootState,
payload: 'some-stuff'
})
}
}
And this could be called in a .vue file with something like this
methods: {
...mapActions('ModuleB', ['myCoolAction']),
}
...
await this.myCoolAction()
PS: IMO the convention is more to name the file module_b.js.

"[vuex] state field foo was overridden by a module with the same name at foobar" with deepmerge helper function in jest

I'm using a helper function to create a store inside my jests. The helper function uses deepmerge to merge the basic configuration with a customized configuration. This results in multiple console warnings
[vuex] state field "cart" was overridden by a module with the same name at "cart"
[vuex] state field "customer" was overridden by a module with the same name at "customer"
[vuex] state field "checkout" was overridden by a module with the same name at "checkout"
store.js (Reduced to a minimum for presentation purpose)
import cart from './modules/cart'
import checkout from './modules/checkout'
import customer from './modules/customer'
Vue.use(Vuex)
export const config = {
modules: {
cart,
customer,
checkout,
},
}
export default new Vuex.Store(config)
test-utils.js
import merge from 'deepmerge'
import { config as storeConfig } from './vuex/store'
// merge basic config with custom config
export const createStore = config => {
const combinedConfig = (config)
? merge(storeConfig, config)
: storeConfig
return new Vuex.Store(combinedConfig)
}
making use of the helper function inside
somejest.test.js
import { createStore } from 'test-utils'
const wrapper = mount(ShippingComponent, {
store: createStore({
modules: {
checkout: {
state: {
availableShippingMethods: {
flatrate: {
carrier_title: 'Flat Rate',
},
},
},
},
},
}),
localVue,
})
How do I solve the console warning?
I believe the warning is somewhat misleading in this case. It is technically true, just not helpful.
The following code will generate the same warning. It doesn't use deepmerge, vue-test-utils or jest but I believe the root cause is the same as in the original question:
const config = {
state: {},
modules: {
customer: {}
}
}
const store1 = new Vuex.Store(config)
const store2 = new Vuex.Store(config)
<script src="https://unpkg.com/vue#2.6.11/dist/vue.js"></script>
<script src="https://unpkg.com/vuex#3.4.0/dist/vuex.js"></script>
There are two key parts of this example that are required to trigger the warning:
Multiple stores.
A root state object in the config.
The code in the question definitely has multiple stores. One is created at the end of store.js and the other is created by createStore.
The question doesn't show a root state object, but it does mention that the code has been reduced. I'm assuming that the full code does have this object.
So why does this trigger that warning?
Module state is stored within the root state object. Even though the module in my example doesn't explicitly have any state it does still exist. This state will be stored at state.customer. So when the first store gets created it adds a customer property to that root state object.
So far there's no problem.
However, when the second store gets created it uses the same root state object. Making a copy or merging the config at this stage won't help because the copied state will also have the customer property. The second store also tries to add customer to the root state. However, it finds that the property already exists, gets confused and logs a warning.
There is some coverage of this in the official documentation:
https://vuex.vuejs.org/guide/modules.html#module-reuse
The easiest way to fix this is to use a function for the root state instead:
state: () => ({ /* all the state you currently have */ }),
Each store will call that function and get its own copy of the state. It's just the same as using a data function for a component.
If you don't actually need root state you could also fix it by just removing it altogether. If no state is specified then Vuex will create a new root state object each time.
It is logged when a property name within the state conflicts with the name of a module, like so:
new Vuex.Store({
state: {
foo: 'bar'
},
modules: {
foo: {}
}
})
therefore this raises the warning.
new Vuex.Store(({
state: {
cart: '',
customer: '',
checkout: ''
},
modules: {
cart: {},
customer: {},
checkout: {},
}
}))
its most likely here
export const createStore = config => {
const combinedConfig = (config)
? merge(storeConfig, config)
: storeConfig
return new Vuex.Store(combinedConfig)
}
from the source code of vuex, it helps indicate where these errors are being raised for logging.
If you run the app in production, you know that this warning wont be raised... or you could potentially intercept the warning and immediately return;
vuex source code
const parentState = getNestedState(rootState, path.slice(0, -1))
const moduleName = path[path.length - 1]
store._withCommit(() => {
if (__DEV__) {
if (moduleName in parentState) {
console.warn(
`[vuex] state field "${moduleName}" was overridden by a module with the same name at "${path.join('.')}"`
)
}
}
Vue.set(parentState, moduleName, module.state)
})
vuex tests
jest.spyOn(console, 'warn').mockImplementation()
const store = new Vuex.Store({
modules: {
foo: {
state () {
return { value: 1 }
},
modules: {
value: {
state: () => 2
}
}
}
}
})
expect(store.state.foo.value).toBe(2)
expect(console.warn).toHaveBeenCalledWith(
`[vuex] state field "value" was overridden by a module with the same name at "foo.value"`
)
Well, I believe there is no need for using deepmerge in test-utils.ts. It is better we use Vuex itself to handle the merging of the module instead of merging it with other methods.
If you see the documentation for Vuex testing with Jest on mocking modules
you need to pass the module which is required.
import { createStore, createLocalVue } from 'test-utils';
import Vuex from 'vuex';
const localVue = createLocalVue()
localVue.use(Vuex);
// mock the store in beforeEach
describe('MyComponent.vue', () => {
let actions
let state
let store
beforeEach(() => {
state = {
availableShippingMethods: {
flatrate: {
carrier_title: 'Flat Rate',
},
},
}
actions = {
moduleActionClick: jest.fn()
}
store = new Vuex.Store({
modules: {
checkout: {
state,
actions,
getters: myModule.getters // you can get your getters from store. No need to mock those
}
}
})
})
});
whistle, In test cases:
const wrapper = shallowMount(MyComponent, { store, localVue })
Hope this helps!

Understanding State and Getters in Nuxt.js: Getters won't working

i'm new to Vue and Nuxt and i'm building my first website in Universal mode with these framework.
I'm a bit confused on how the store works in nuxt, since following the official documentation i can't achieve what i have in mind.
In my store folder i have placed for now only one file called "products.js", in there i export the state like this:
export const state = () => ({
mistica: {
id: 1,
name: 'mistica'
}
})
(The object is simplified in order to provide a cleaner explanation)
In the same file i set up a simple getter, for example:
export const getters = () => ({
getName: (state) => {
return state.mistica.name
}
})
Now, according to the documentation, in the component i set up like this:
computed: {
getName () {
return this.$store.getters['products/getName']
}
}
or either (don't know what to use):
computed: {
getName () {
return this.$store.getters.products.getName
}
}
but when using "getName" in template is "undefined", in the latter case the app is broken and it says "Cannot read property 'getName' of undefined"
Note that in the template i can access directly the state value with "$store.state.products.mistica.name" with no problems, why so?
What am i doing wrong, or better, what didn't i understand?
Using factory function for a state is a nuxt.js feature. It is used in the SSR mode to create a new state for each client. But for getters it doesn't make sense, because these are pure functions of the state. getters should be a plain object:
export const getters = {
getName: (state) => {
return state.mistica.name
}
}
After this change getters should work.
Then you can use the this.$store.getters['products/getName'] in your components.
You can't use this.$store.getters.products.getName, as this is the incorrect syntax.
But to get simpler and more clean code, you can use the mapGetters helper from the vuex:
import { mapGetters } from "vuex";
...
computed: {
...mapGetters("products", [
"getName",
// Here you can import other getters from the products.js
])
}
Couple of things. In your "store" folder you might need an index.js for nuxt to set a root module. This is the only module you can use nuxtServerInit in also and that can be very handy.
In your products.js you are part of the way there. Your state should be exported as a function but actions, mutations and getters are just objects. So change your getters to this:
export const getters = {
getName: state => {
return state.mistica.name
}
}
Then your second computed should get the getter. I usually prefer to use "mapGetters" which you can implement in a page/component like this:
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters({
getName: 'products/getName'
})
}
</script>
Then you can use getName in your template with {{ getName }} or in your script with this.getName.

How can I use Vuex modules state without nested objects?

I'm trying to convert existing Vuex state to modules. I'm trying to use modules like this:
const moduleA = {
state: {},
mutations: {
update (state, payload) { // payload is an object
state = payload // doesn't work
}
},
I'm registering modules:
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
The question is: is it possible to use state without nesting as I'm trying to do? Or the only way is to have something like:
const moduleA = {
state: {
one: {}
},
mutations: {
update (state, payload) {
state.one = payload // it works
},
},
}
Ideally, I'd like to have the same structure as it was before and being able to get the state as state.a instead of state.a.one
Thank you
Yes you can -- just refactor the modules into separate files and then use an index file to bring them all together:
import Vue from 'vue'
import Vuex from 'vuex'
import users from './store.users.js'
import entries from './store.entries.js'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
users,
entries
}
})
export default store
Then in each module's file (e.g. store.entries.js, you can follow the pattern you're familiar with, but with namespaced set to true:
const module = {
namespaced: true,
state: {},
getters: {},
mutations: {},
actions: {}
}
module.actions.update = ({ commit, state }, payload) => {
// commit, state, etc refer to the local store
}
export default module
For files using the store, you can import the index and then call by module:
import store from '../stores/store.index.js'
// ...
store.dispatch('entries/update', payload)
You can use state = Object.assign(state, payload). But note that this means you keep all existing props and shallow merge new ones in.
You cannot create a new state object unless you lift the logic up to the global namespace and use dynamic module registration