vuejs / vuex

🗃️ Centralized State Management for Vue.js.
https://vuex.vuejs.org
MIT License
28.42k stars 9.58k forks source link

Define state when preserved is true, but there is no state to preserve #2083

Open thiagosantos opened 3 years ago

thiagosantos commented 3 years ago

Version

3.4.0

Reproduction link

codesandbox.io

Steps to reproduce

The fast way to verify this bug is creating a project from scratch, adding vuex, creating a module (I did it in a separate file), setting the namespace to true, registering it like "store.registerModule('bar', module, {preserveState:true})". Now at a vue file call from a a method "this.$store.dispatch('bar/setValue', {name:'foo'})".

What is expected?

The value is to be set correctly.

What is actually happening?

Throws a error.

[Vue warn]: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'user')"


Vuex handles modules defined in the constructor options different from those registered with store.registerModule. For registerModule calls, the modules pass for a variety of checks before being embedded in the global store.

When checking in "installModule" if the module should be at the root and if the "state" should not be preserved is not observed that if "hot" is set to true, but the state was not defined before throws an error inside the mutation called to change state like "Cannot read properties of undefined (reading 'foo')".

That occurs because it was preserved a no existing state. That's why we should check if the state already exists if so, it will be preserved otherwise we set the default from the module.

I need the value to be preserved due to the vuex-persistedstate that I'm using and I don't want to get overridden, but at the same time if no state is to be preserved the module default state should be defined.

pickmonster commented 2 years ago

same error

thiagosantos commented 2 years ago

@pickmonster I made a patch and committed other day https://github.com/vuejs/vuex/pull/2084/files