How to use Pinia outside a component in js file
Asked Answered
A

3

12

I am migrating from vue 4.x to pinia, one of my file needs api key from store. But I can't make it work even though I follow the Pinia documentation . here is how I use pinia

// Repository.ts

import axios from "axios";

import { createPinia } from 'pinia'
import { useAuthStore } from '../stores/auth-store'
const pinia=createPinia();
let authStore = useAuthStore(pinia);
const baseURL = 'http://127.0.0.1:5678/res-api';

export default axios.create({
  baseURL,
  headers:{"Authorization":"Bearer " + authStore.getToken,
"Accept":"application/json"},
  
});

Expected result : to get the token from the store.

Console error

Uncaught ReferenceError: Cannot access 'useAuthStore' before initialization
    at Repository.ts:6:17
    

Note: this working inside a component 
Adila answered 11/1, 2022 at 18:7 Comment(1)
Have you tried to set headers in request interceptors and call useAuthStore in the config function?Cano
T
19

You can solve this by importing the store inside the interceptors

import axios from "axios";
import { useAuthStore } from '../stores/auth-store';

const axiosClient = axios.create({
    baseURL: 'http://127.0.0.1:5678/res-api'
});

axiosClient.interceptors.request.use((config) => {
    const authStore = useAuthStore();
    config.headers.Authorization = `Bearer ${authStore.getToken}`;
    config.headers.Accept = "application/json";
    return config
})

export default axiosClient;

This discussion may help you: Go to GitHub discussion

Tisbee answered 22/5, 2022 at 20:4 Comment(0)
U
3

According to the documentation the pinia you created must go as a parameter to app.use. Not only that, but useAuthStore must be a store defined with defineStore and must not take a parameter. I'll leave a link that can help you, it doesn't create the store but you can browse the side menu to see several examples.

https://pinia.vuejs.org/core-concepts/outside-component-usage.html

Unteach answered 9/2, 2022 at 18:43 Comment(0)
P
0

Here is my sample project to demo the issue: https://codesandbox.io/s/infallible-shamir-sxrlb9.

The main cause here is that you cannot use Pinia's stores before passing it to the Vue's app. So given following code:

const pinia = createPinia(); // line 1

createApp(App).use(pinia).mount("#app"); // line 2

You cannot trigger any store in between line 1 and 2, but only after line 2.

In your code, likely you trigger an axios call before creating Vue app/add Pinia to Vue app. Please try to delay that axios call to trigger after Vue app's setup is complete.

Pretorius answered 28/2, 2022 at 2:29 Comment(1)
Actually you only need to use(pinia), mounting the app is not necessary. js const pinia = createPinia(); createApp(App).use(pinia); // You may call useAuthStore here app.mount("#app"); Gilmore

© 2022 - 2024 — McMap. All rights reserved.