Search code examples
vue.jsvuejs3pinia

Component doesn't update on pinia state change


I have a Pinia store, which is being updated by user interaction. After being updated, the UI component doesn't update. I have tried a few different ways, such as changing the pinia getter to an action, not destructuring the pinia store, using storeToRefs or using a ref.

The Store

export const useSomeStore = defineStore('someStore', {
  state: () => {
    return { someArray: [] }
  }
},
getters: {
  getFilteredArray: (state) => {
    return (id) => state.someArray.filter(i => i._id === id);
  }
});

The Component (only script part)

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

  // This works initially, but it's seemingly not reactive
  const foo = someStore.getFilteredArray(props.someProp);
<script>

How do I make foo reactive?


Solution

  • The documentation states that, when "passing arguments" to a getter, that getter is not cached anymore (understand non-reactive) since it becomes a simple function that doesn't change.

    Therefore, you must use the computed composable to make it reactive, just as you would with any other function:

    import { computed } from 'vue'
    import { useSomeStore } from '@/stores/someStore'
    
    const someStore = useSomeStore();
    const foo = computed(() => someStore.getFilteredArray(props.someProp));