[Vuejs]-How to get a reference to the current pinia store from a (composable) action?

0👍

I don’t know if it’s the best way or not, and you may also consider @Estus Flask’s comment :

It makes more sense to create a wrapper for defineStore here

But I ended up with passing useMyStore as a parameter.

Note though that it should be called in each generic action, since the store is not created at useGeneric() execution.

Here what it looks like :

// Here is a generic composable:
function export useGeneric(getStore:any) { //Typing here is quite hard, maybe use an interface to avoid the any is the best solution
  function genericAct(){
    const store = getStore(); // This is what I need
    store.a.value = 42;
    store.act2(); // This action should be implemented in the store using the generics
  }
  return {genericAct}
}

// Here is an example store using it
export const useMyStore = defineStore('myStore', () => {
  const a = ref(1);
  const b = ref(1);
  const {genericAct} = useGeneric(useMyStore);
  function act2(){
    b.value = 43;
  }
  return {a, b, genericAct, act2};
}

Leave a comment