Error when i call an axios method in pinia

205 views Asked by At

In my vue3 project, I take token from pinia then add it to the request header

utils/request.js

import axios from 'axios'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import router from '@/router'

const baseURL = 'xxxx'
const userStore = useUserStore()
const instance = axios.create({
  baseURL: baseURL,
  timeout: 1000
})

instance.interceptors.request.use(
  function (config) {
    // take token from pinia and add it in request header.
    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

//........

export default instance
export { baseURL }

It works well, but now I have a method which used to get use info from service.

import request from '@/utils/request.js'

//......

export const userGetInfoService = () => request.get('/my/userinfo')

In my store, I wanna call this method to get user Info and save it in pinia:

import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userGetInfoService } from '../../api/user'

export const useUserStore = defineStore(
  'big-user',
  () => {
    //.......

    const userInfo = ref({})

    const getUserInfo = async () => {
      const result = await userGetInfoService()
      userInfo.value = result.data.data
    }

    return {
      //......
      userInfo,
      getUserInfo
    }
  },
  {
    persist: true
  }
)

But once i call this method in store, It shows

enter image description here

enter image description here

I am not sure why i can't call this method in store

1

There are 1 answers

1
yoduh On BEST ANSWER

Using pinia outside of a component is explained in the documentation here.

Your router.js code runs before app.use(pinia) does in main.js, so Pinia is not initialized at the time you call useUserStore(), which is why you get an error. You can confirm the timing of this with some console.logs.

Since your axios interceptor function shouldn't be called until well after pinia is active and your app is running, the solution is to define your store inside the interceptor:

instance.interceptors.request.use(
  function (config) {
    const store = useExampleStore()
    ...
  }
)