0

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?

KorbenDose
  • 797
  • 1
  • 7
  • 23

2 Answers2

3

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));
Vivick
  • 3,434
  • 2
  • 12
  • 25
  • Thanks for the suggestions. I have also tried `computed` and have also retried after reading your answer. Unfortunately it still doesn't update `foo`. I have checked the store for errors, but the actual state is being updated. What else could I be missing? – KorbenDose Aug 12 '23 at 14:17
  • 1
    I just found out that the `getFilteredArray` getter is only being called once. After updating the state, `foo` is being reevaluated, but the actual getter is not being called again. – KorbenDose Aug 12 '23 at 14:31
  • @KorbenDose The question lacks https://stackoverflow.com/help/mcve . If the problem persists, consider providing the way you use foo. Generally it's what the answer shows and explains. getFilteredArray itself is supposed to be called once but the function it returns is called every time you call it. – Estus Flask Aug 12 '23 at 14:49
  • @EstusFlask I tried to reduce the problem to the essential parts. After finding the error in a different part of the code, I can confirm that the provided solution works. Thanks again. – KorbenDose Aug 12 '23 at 15:22
2

it`s recommended to use the computed prop with the stores in general to be reactive :

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

// Define a computed property that tracks the getter
const foo = Vue.computed(() => someStore.getFilteredArray(props.someProp));
</script>
Mohamed Mostafa
  • 520
  • 2
  • 10