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
}
});
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