vuex: state field "foo" was overridden by a module with the same name at "foo" - vue.js

I am getting this warning in the console:
[vuex] state field "foo" was overridden by a module with the same name at "foo"
What does it mean and what can I have done wrong?

This is a new warning added in Vuex 3.1.2.
https://github.com/vuejs/vuex/releases/tag/v3.1.2
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: {}
}
})
If you attempt to access state.foo you might expect the value to be 'bar' but it will actually refer to the state of the foo module.
You would fix this problem by removing the property from the state object, or by renaming either the property or the module.
Here's a small example that logs the relevant warning and shows the resulting value of state.foo:
const store = new Vuex.Store({
state: {
foo: 'bar'
},
modules: {
foo: { state: { flag: 2 } }
}
})
console.log(store.state.foo)
<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>
Update:
This warning can also be logged if you create multiple stores using the same configuration object, e.g. during testing.
Here's an example:
const config = {
state: {},
modules: {
foo: {}
}
}
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>
The problem is that the configuration includes a root state object. The first store adds the foo module to that object. When the second store tries to do the same thing it finds that the property already exists and logs the error.
If the root state object is empty, like it is in my example, then it could just be removed. However, assuming it isn't empty you'd fix this by changing it to a function instead:
const config = {
state () {
return {
/* state properties here */
}
},
modules: {
foo: {}
}
}
This works exactly the same way as the data function for a component.

Related

"[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!

In Vue - what's the difference between this.$data.foo vs this.foo?

I'm curious since both seem to work and I'm having trouble finding an answer in the Vue docs. Is there a reason you should refer to data in Vue as this.$data.whatever vs just this.whatever?
The data with $ prefix is specifically defined for accessing vue data property rather than user defined property.
For eg.
var data = { foo: 'foo' } // user defined data
var inst = new Vue({ data: { foo: 'foo' } }) // data - built-in vue property
data.foo // user defined data
inst.$data.foo // vue property - data
When you're inside the Vue hooks, you can just simply use this.foo for eg. inside computed method.
For more detail, you can see the docs
The $data attribute is used to access the data property outside the component:
var data = { a: 1 }
// direct instance creation
var vm = new Vue({
data: data
})
vm.a // => 1
vm.$data === data // => true
// must use function when in Vue.extend()
var Component = Vue.extend({
data: function () {
return { a: 1 }
}
})
Source: https://v2.vuejs.org/v2/api/#data

Vuex Modules Creating Nested Object

I have been trying to separate my store.js file into multiple store modules. I have it working (somewhat), but it also created kind of a big issue.
In my initial one single file store, let's suppose this is my state object:
state: { user: '' }
And the output in the Vuex developer tools shows the user object as it should:
User: { name: "John", age: 33 }
But after splitting the the store into modules the user object in the Vuex developer tools is as follows:
User: { User: { name: "John", age: 33 } }
So it creates a new object using the name I give it in the modules object and import in the main store.js file, which then contains the "true" user object.
Is there any way to have it not create a new object and keep it the same as if the entire store lived inside the store.js file?
-Sergio
EDIT:
Here is the structure of my files:
store
store.js
modules
user.js
The code in the modules/user.js:
const state = { User: '' }
const mutations = { ... }
const actions = { ... }
export default { state, mutations, actions }
The code in my store.js
import User from './modules/user';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
User
}
});
Prior to externalizing the store I would get in Vuex dev tools:
User: { name: "John", age: 33 }
After externalizing the store I get:
User: { User: { name: "John", age: 33 } }
It's nesting User from the modules/user file inside the User in the store.js file. I want to avoid that (if its possible) so that I don't have to change everything in my components/template files.
The 'extra parent object' shown in the Vue Devtools is actually the namespaced module. If you set the User module's namespace attribute to false, the User state will no longer be placed within a namespaced object and will instead be
registered under the global namespace. (Vuex Namespacing)
Setting namespace: false is totally fine if you don't expect User function names to conflict with other modular state function names.
const store = new Vuex.Store({
modules: {
User: {
namespaced: false,
state: { user: '' },
...
}
}
}

Property or method "$v" is not defined using Vuelidate

Error:
[Vue warn]: Property or method "$v" is not defined on the instance but
referenced during render. Make sure that this property is reactive,
either in the data option, or for class-based components, by
initializing the property. See:
https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in
---> at resources\assets\js\components\products\Product_create.vue
I'm using Vue.js and Vuelidate as validator,
I've copied and pasted this code from here https://jsfiddle.net/Frizi/b5v4faqf/ but it still doesn't work :
Vue Component :
<template >
<input v-model="$v.text.$model" :class="status($v.text)">
<!-- <pre>{{ $v }}</pre> -->
</template>
<script>
import { required, minLength, between } from 'vuelidate/lib/validators'
export default {
data() {
return {
text: ''
}
},
validations: {
text: {
required,
minLength: minLength(5)
}
},
methods: {
status(validation) {
return {
error: validation.$error,
dirty: validation.$dirty
}
}
}
}
</script>
App.js
require('./bootstrap');
window.Vue = require('vue');
window.VueRouter = require('vue-router').default;
window.VueAxios = require('vue-axios').default;
window.Axios = require('axios').default;
window.VueFormWizard = require('vue-form-wizard');
window.Vuelidate = require('vuelidate').default;
import 'vue-form-wizard/dist/vue-form-wizard.min.css';
Vue.use(VueRouter,VueAxios,axios,VueFormWizard,Vuelidate);
const ProductOptionCreate = Vue.component('po-create',require('./components/products/ProductOption_create.vue'));
const ProgressModal = Vue.component('vue-modal',require('./components/ProgressModal.vue'));
const ProductIndex = Vue.component('product-list',require('./components/products/Product_index.vue'));
const productshow = Vue.component('productshow',require('./components/products/ProductOption_show.vue'));
const ProductCreate = Vue.component('product-create',require('./components/products/Product_create.vue'));
const app = new Vue({
el:'#app',
});
What's wrong with this code?
The problem is that $v is not defined at a component level, and it is because of the order of your components, you need to reorder them like so:
// ... other stuff
import 'vue-form-wizard/dist/vue-form-wizard.min.css';
Vue.use(Vuelidate);
const ProductOptionCreate = // ... rest of your components
I think the problem was that the validation was declared within the data property of the component and not as a direct property of the component.
So
export default {
validations: {
text: {
required,
minLength: minLength(5)
},
data() {
return {
text: ''
}
},
},
........
instead of
export default {
data() {
return {
text: ''
}
},
validations: {
text: {
required,
minLength: minLength(5)
}
The reason $v is not available on your instance is because you haven't instantiated the Vuelidate plugin. And that's because you tried to streamline the call to Vue.use().
Your current Vue.use() call only instantiates the first plugin (VueRouter) and passes VueAxios plugin object as VueRouter's config object. All subsequent arguments are ignored.
To streamline your calls to Vue.use(), you can't simply add more arguments to it.
Instead of this erroneous syntax (which breaks instantiation of all but first plugin):
Vue.use(VueRouter, VueAxios, axios, VueFormWizard, Vuelidate);
... you could use:
[[VueRouter], [VueAxios, axios], [VueFormWizard], [Vuelidate]]
.forEach(args => Vue.use(...args));
With Typescript: unfortunately, TS parser wrongly includes 0 arguments as a possible outcome of the spread operator in the above case, so you'd need to suppress it using:
[
[VueRouter],
[VueAxios, axios],
[VueFormWizard],
[Vuelidate]
/* #ts-ignore: TS2557, TS wrong about array above having empty members */
].forEach(args => Vue.use(...args));
... at least for now ("typescript": "^3.9.7").
The above syntax is the exact equivalent of:
Vue.use(VueRouter);
Vue.use(VueAxios, axios);
Vue.use(VueFormWizard);
Vue.use(Vuelidate); // <= this is what you were missing, basically
// but your syntax also broke VueAxios and VueFormWizard install
On a personal note: although a tad more repetitive, I actually find the Vue.use() syntax cleaner in this case (more readable).
The validations should be defined in a component in order to initialize this.$v
I had a typo and didn't realized I was declaring validations inside methods.
methods: {
validations: {
isUScitizen: { required },
},
}
And I was trying to access this.$v which was undefined because the component didn't had validations defined.
You must specify this.$v and there will be no error

what is vuex-router-sync for?

As far as I know vuex-router-sync is just for synchronizing the route with the vuex store and the developer can access the route as follows:
store.state.route.path
store.state.route.params
However, I can also handle route by this.$route which is more concise.
When do I need to use the route in the store, and what is the scenario in which I need vuex-router-sync?
Here's my two cents. You don't need to import vuex-router-sync if you cannot figure out its use case in your project, but you may want it when you are trying to use route object in your vuex's method (this.$route won't work well in vuex's realm).
I'd like to give an example here.
Suppose you want to show a message in one component. You want to display a message like Have a nice day, Jack in almost every page, except for the case that Welcome back, Jack should be displayed when the user's browsing top page.
You can easily achieve it with the help of vuex-router-sync.
const Top = {
template: '<div>{{message}}</div>',
computed: {
message() {
return this.$store.getters.getMessage;
}
},
};
const Bar = {
template: '<div>{{message}}</div>',
computed: {
message() {
return this.$store.getters.getMessage;
}
}
};
const routes = [{
path: '/top',
component: Top,
name: 'top'
},
{
path: '/bar',
component: Bar,
name: 'bar'
},
];
const router = new VueRouter({
routes
});
const store = new Vuex.Store({
state: {
username: 'Jack',
phrases: ['Welcome back', 'Have a nice day'],
},
getters: {
getMessage(state) {
return state.route.name === 'top' ?
`${state.phrases[0]}, ${state.username}` :
`${state.phrases[1]}, ${state.username}`;
},
},
});
// sync store and router by using `vuex-router-sync`
sync(store, router);
const app = new Vue({
router,
store,
}).$mount('#app');
// vuex-router-sync source code pasted here because no proper cdn service found
function sync(store, router, options) {
var moduleName = (options || {}).moduleName || 'route'
store.registerModule(moduleName, {
namespaced: true,
state: cloneRoute(router.currentRoute),
mutations: {
'ROUTE_CHANGED': function(state, transition) {
store.state[moduleName] = cloneRoute(transition.to, transition.from)
}
}
})
var isTimeTraveling = false
var currentPath
// sync router on store change
store.watch(
function(state) {
return state[moduleName]
},
function(route) {
if (route.fullPath === currentPath) {
return
}
isTimeTraveling = true
var methodToUse = currentPath == null ?
'replace' :
'push'
currentPath = route.fullPath
router[methodToUse](route)
}, {
sync: true
}
)
// sync store on router navigation
router.afterEach(function(to, from) {
if (isTimeTraveling) {
isTimeTraveling = false
return
}
currentPath = to.fullPath
store.commit(moduleName + '/ROUTE_CHANGED', {
to: to,
from: from
})
})
}
function cloneRoute(to, from) {
var clone = {
name: to.name,
path: to.path,
hash: to.hash,
query: to.query,
params: to.params,
fullPath: to.fullPath,
meta: to.meta
}
if (from) {
clone.from = cloneRoute(from)
}
return Object.freeze(clone)
}
.router-link-active {
color: red;
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://unpkg.com/vuex/dist/vuex.js"></script>
<div id="app">
<p>
<router-link to="/top">Go to Top</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<router-view></router-view>
</div>
fiddle here
As you can see, the components are well decoupled from vuex and vue-router's logic.
This pattern sometimes works really effectively for the case that you're not concerned about the relationship between current route and the value returned from vuex's getter.
I saw this thread when I was learning Vue. Added some of my understanding on the question.
Vuex defines a state management pattern for Vue applications. Instead of defining component props and passing the shared state through props in all the places, we use a centralized store to organize the state shared by multiple components. The restriction on state mutation makes the state transition clearer and easier to reason about.
Ideally, we should get / build consistent (or identical) views if the provided store states are the same. However, the router, shared by multiple components, breaks this. If we need to reason about why the page is rendered like it is, we need to check the store state as well as the router state if we derive the view from the this.$router properties.
vuex-router-sync is a helper to sync the router state to the centralized state store. Now all the views can be built from the state store and we don't need to check this.$router.
Note that the route state is immutable, and we should "change" its state via the $router.push or $router.go call. It may be helpful to define some actions on store as:
// import your router definition
import router from './router'
export default new Vuex.Store({
//...
actions: {
//...
// actions to update route asynchronously
routerPush (_, arg) {
router.push(arg)
},
routerGo (_, arg) {
router.go(arg)
}
}
})
This wraps the route updates in the store actions and we can completely get rid of the this.$router dependencies in the components.