Pinia respond to changes in one store from another

Viewed 47

I have two stores, A and B. I want B to react to changes in A's state.

A has an action fetchData that completes as expected, and a getter/setter pair activeObject. User navigation dictates activeObject. B has separate concerns but derives some state from A in its own getter, bFromA.

The docs on accessing another store's getter say you can "directly use it", but in practice this isn't working. My components that consume bFromA don't react to changes in activeObject based on the code below. If the hmr updates without a complete page reload, I do see the expected state change.

it seems the only way to react to changes from A in B is to follow the action subscription approach and subscribe to fetchData. This seems completely counter to the docs, and what I think Pinia should be able to do without subscriptions. What's wrong with my approach?

In reality, I have more stores than this. Merging A and B is not an option.

Store A

export const useStoreA = defineStore('storeA', {
  state: () => ({
    _activeObject: { someProp: true },
  }),
  getters: {
    activeObject: (state) => state._activeObject,
  },
  actions: {
    fetchData() { 
      /* network call */ 
    },
    setActiveObject(obj) {
      this._activeObject = obj;
    }
  }
});

Store B

export const useStoreA = defineStore('storeB', {
  state: () => ({
    /* some values */
  }),
  getters: {
    bFromA(state) {
      const storeA = useStoreA();
      /* have tried both computed and plainly using storeA.activeObject */
      const { activeObject } = storeToRefs(storeA);
      return activeObject.value?.someProp ?? true;
    }
  },
});

Component consuming B

setup() {
  const storeB = useStoreB();
  return {
    bFromA: computed(() => storeB.bFromA);
  }
}
0 Answers
Related