'vue3 resuable computed properties

I tried creating Singleton service files with vue3 to have reusable computed properties (define once , then just reuse on every other call)

Normally with composition api pattern each time you do useX() every computed property inside is is redefined, this is ok for small project with little amount of computed props but for my scenario many computed props are reused on multiple components

so here what I did :

function factory(){
 const x = computed(()=> store.getters['x']);

 function updateX(){
   store.commit('setX',newXValue);
 }

 return { x };
}

export default function useY() {
  return SingletonServiceProvider.Create<ReturnType<typeof factory>>(factory);
}
export default class SingletonServiceProvider {
  static Create<T>(factory: (...args: unknown[]) => T): T {
    // TODO define proper type
    // @ts-ignore
    if (!factory.Instance) {
      // @ts-ignore
      factory.Instance = factory();
    }

    // @ts-ignore
    return factory.Instance;
  }
}

Now the problem I am facing: the x prop is properly filled the first time. But If I change the store value the x computed property is not updated!!!
I even added a store.watch and even this is nor triggered too!!

  store.watch(
    (state, getters) => getters['x'],
    (value, oldValue) => {
      console.log('...................xxxxx', { ...value }, { ...oldValue });
    },
  );

What am I doing wrong? Is this a vue/vuex limit ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source