Issue with nested state change reactivity #2608
-
I've got a weird situation where components have pinia state props passed as a component prop to determine whether to show error messages or not. When I call For example, defining a simple store like this: export const useFormStore = defineStore('formState', {
state: () => ({
fields: {
email: {
hasError: false,
},
}
}),
actions: {
reset(){
this.$reset()
}
} And a simple child component called "FormField.vue" <template>
<div class="text-red" v-if='hasError'>This is required!</div>
<input type="text" label="email"> </input>
</template>
<script setup>
const props = defineProps({
hasError: {
default: false,
required: true
}
})
</script> And our parent component: <template>
<FormField :has-error="fields.email.hasError" />
<button @click="handleReset">Reset</button>
</template>
<script setup>
import { useFormState } from '@/stores/form.store.js'
const { fields, reset } = useFormState()
function handleReset(){
reset();
}
</script> In this example, when the 'Reset' button gets clicked, we can console.log our However, if in our this.$state.fields.email.hasError = false It works as expected. That doesn't make sense to me given state objects are reactive, and manually changing the prop value of the state object reactively updates the component state. Anyone run in to this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
You lose reactivity if you destructure the store: const { fields, reset } = useFormState() You should just do |
Beta Was this translation helpful? Give feedback.
-
@posva thanks for the follow-up. Destructuring using What's interesting is that I did try modifying my store to be a return {
...storeToRefs(state),
someAction,
someAction2,
} But that didn't seem to work either. Could be a syntax issue on my side I suppose. |
Beta Was this translation helpful? Give feedback.
You lose reactivity if you destructure the store:
You should just do
store = useFormState()
and usestore.fields
when needed. If you really need to extract them see https://pinia.vuejs.org/core-concepts/#Destructuring-from-a-Store