Given two Vue stores using Pinia, useStoreA and useStoreB, how can useStoreA update a state property in useStoreB?
import { defineStore } from 'pinia'; export const useStoreA = defineStore('storeA', { state: () => ({ countA: 0 }), actions: { incrementB() { // What goes here? } } }); export const useStoreB = defineStore('storeB', { state: () => ({ countB: 0 }), actions: { increment() { this.countB++; } } });
Remember to call the other store's function by first creating its instance inside the action.
In Pinia, to interact with another store, you must first create its instance by calling its useStore function. Then you can call its actions or access its state. Option B correctly creates storeB instance and calls increment().
Assuming the stores from the previous challenge, what will be the value of storeB.countB after calling storeA.incrementB() two times?
const storeA = useStoreA(); const storeB = useStoreB(); storeA.incrementB(); storeA.incrementB(); console.log(storeB.countB);
Each call to incrementB() calls storeB.increment() once.
Each call to storeA.incrementB() calls storeB.increment(), which increases countB by 1. Two calls increase countB from 0 to 2.
Identify the correct syntax to import and use useStoreB inside useStoreA for store-to-store interaction.
Remember to import the store as a named import and call it as a function to get the instance.
Option C correctly imports useStoreB as a named import and calls it to get the store instance before updating state. Option C uses CommonJS require which is invalid in ES modules. Options A and C try to access state on the function itself, not the instance.
Consider two Pinia stores where storeA updates storeB's state directly. The UI bound to storeB.countB does not update after the change. Why?
export const useStoreA = defineStore('storeA', { actions: { updateB() { const storeB = useStoreB(); storeB.countB = 10; // direct assignment } } });
Think about how Vue tracks changes and updates the UI.
Directly assigning to a state property outside of a Pinia action can bypass Vue's reactivity system, especially if the property was not reactive or the assignment does not trigger reactivity. The recommended way is to update state inside actions to ensure reactivity and UI updates.
You want two Pinia stores to share some state but keep them loosely coupled. Which approach is best?
Think about modularity and avoiding tight coupling.
Creating a dedicated shared store for common state is the best practice. It keeps stores decoupled, avoids direct dependencies, and leverages Pinia's reactivity. Direct imports cause tight coupling, global variables break reactivity, and manual sync is error-prone.