Vue · Middle · Question 42 of 75
How do you use a store outside of a component, e.g. in a router guard?
router.beforeEach((to) => {
const auth = useAuthStore();
if (to.meta.requiresAuth && !auth.user) return "/login";
});- ✓Correct answer: Call
useStore()inside the function that runs after Pinia is installed, not at module top level - 2Import the store instance created at module load
- 3Stores can't be used outside components
Explanation
At module top level the Pinia instance may not be active yet (and in SSR it would be shared between requests). Calling the hook inside the guard uses the app's active Pinia.