How to access Pinia outside of Vue component, in Vue app #687
-
I am using Pinia in a Vue app and now I need to access a Pinia store from within an Axios interceptor; a standalone TypeScript file, effectively outside of the normal Vue flow; outside of a component. import App from '@/App.vue' is in main.ts, in Vue, as expected. And now am I supposed to import App from '@/App.vue' yet again, to use a Pinia store outside of a component, as per Pinia's documentation? The App.vue calls several APIs to initialize the Vue app. It does not seem to make sense to import App.vue again, outside of main.ts. Any ideas as to how to access the same store in a Vue component and at the same time, access (and modify) such store from within a TypeScript file? Many thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 7 replies
-
No you do not import the App again. You would simply import the store you want to use with something like You can then change the state, call actions etc. from within the interceptor. It's important you call the store within the interceptor because if you do it outside then Pinia may not have initialised yet and you will get a console warning/error. This is all well documented at https://pinia.esm.dev/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component |
Beta Was this translation helpful? Give feedback.
-
Thank you so much for your help. I noticed what the problem was. Previously I was importing the store outside of the interceptor. When I switched to pinia, I just changed the same line to use pinia, not understanding the fact that pinia needed to be initialized first, as you said. I very much appreciate your time to help on the matter. Switching from Vuex requires a few slight changes in the way things are imported. I really like pinia's simplicity and ease of use :) |
Beta Was this translation helpful? Give feedback.
-
@BenShelton @iknowmagic Thank you! |
Beta Was this translation helpful? Give feedback.
No you do not import the App again. You would simply import the store you want to use with something like
import { useCounterStore } from '@/stores/counter'
and then callconst counterStore = useCounterStore()
WITHIN the interceptor (of course, replace with the actual name of your store).You can then change the state, call actions etc. from within the interceptor. It's important you call the store within the interceptor because if you do it outside then Pinia may not have initialised yet and you will get a console warning/error.
This is all well documented at https://pinia.esm.dev/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component