0

I have a Vue component that modifies a Pinia state and is reactive to the state being updated. This component is something similar to:

<script setup>
import { useStore } from '@/stores/myStore/';
import { reactive } from 'vue';

// Getting the store and using reactive form for the dropdown
const myStore = useStore();
const entryForm = reactive({storeBool: myStore.theBool});

// Function to mutate the state
const onChange = () => {
  myStore.theBool= (entryForm.storeBool=== 'true')
}
</script>

<template>
  <select v-model="entryForm.storeBool" @change="onChange()">
    <option value=false>Option 1</option>
    <option value=true>Option 2</option>
  </select>
</template>

This component is working fine, where selecting a new dropdown value will mutate the state. I have another component that is importing the same store and uses a function in a button to myStore.$reset(). I can see the state value is being changed, but the dropdown is not reacting to the state change. How can I have the dropdown show the reset state?

This reset button component:

<script setup>
import { useStore } from '@/stores/myStore/';
const myStore = useStore();


const resetClick = () =>{
    myStore.$reset();
}
</script>

<template>
    <button @click="resetClick()"></button>
</template>
Yolo_chicken
  • 1,221
  • 2
  • 12
  • 24
  • 1
    You decoupled form state from a store by using myStore.theBool once in setup. If this is not intended, use a watcher on the store – Estus Flask Feb 27 '23 at 23:17
  • Is the way I'm mutating the state with the first component an inefficient way? I'm new to Pinia, and not always sure I'm doing things the "Pinia Way" – Yolo_chicken Feb 28 '23 at 12:26
  • 1
    It's not inefficient, it depends on the result that you need. If you need local state to update store but not vice versa then it's correct. Otherwise it doesn't. If you need a store to be immediately updated (this is not always so) then it makes sense to use a computed or a ref that's linked to the store. Pinia has storeToRefs for this purpose – Estus Flask Feb 28 '23 at 12:33
  • I do want the store value to update the component, so would I use `$subscribe` to the state and this would then watch the store value to update the component? – Yolo_chicken Feb 28 '23 at 12:50
  • 1
    You can use `watch`, and as I said, if you keep local and store state always in sync, you don't need local state, you can update the store directly – Estus Flask Feb 28 '23 at 12:58

0 Answers0