3

I have a Vue.js 3 project where I want to use a global axios instance in some .vue components and also in a pinia store.

My main.js file has axios globally configured like this

const axiosInstance = axios.create({
    baseURL: "http://localhost:8000/",
    headers: {
        "Content-Type": "application/json"
    }
});
const app = createApp(App);
app.config.globalProperties.$http = axiosInstance;
const pinia = createPinia();
app.use(pinia);

//other code...

In .vue components I can axios via $http just fine like this.

methods: {
    async debug() {
      const response = await this.$http.get("get-dates");
      console.log(response.data);
    }
}

But when I try to use this.$http in a pinia store it is undefined. I also noticed that all global variables like $route are all undefined as well.

export const useDateStore = defineStore("dateStore", {
    state: () => ({
        allowedDates: []
    }),
    actions: {
        async fetchAvailableDates() {
            //how I normally use axios
            const response = await axios.get("http://localhost:8000/get-dates");
            //how I want to use axios
            const response2 = await this.$http.get("get-dates");

            console.log(this.$http); //gives undefined
        }
});

2

1 Answer 1

5

With Pinia, you don't have access to global properties. but it's possible to pass using the use()

You will need to change the pinia code and add the context

  actions: {
    async fetchAvailableDates() {
      const response = await this.$http.get("get-dates");
      console.log(response.data);
    }
  }

On the main.js pass the properties, like this:

const pinia = createPinia();
pinia.use(({ store }) => {
  store.$http = app.config.globalProperties.$http;
});
app.use(pinia);

and use that you you want

2
  • 1
    It's this.$http and not context.$http. Action params are the arguments that are passed to them Commented Mar 25, 2023 at 18:59
  • That fixed it for me. The context parameter does not to get passed to actions tho, as said by @EstusFlask. Thank you so much!
    – Philip
    Commented Mar 25, 2023 at 19:09

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.