How to inject $axios into Pinia store SSR

Viewed 1766

I'm trying to inject my axios instance into the store so that I'm able to login into the app but unfortunately I'm being unable to. I have the followed boot file

import { boot } from 'quasar/wrappers';
import axios from 'axios';
import type {AxiosResponse} from 'axios';
import type { StatusCodes } from 'http-status-codes';

export type WrappedResponse = { response?: AxiosResponse };

export const isError = (e: WrappedResponse, statusCode: StatusCodes) =>
  e.response && e.response.status === statusCode;

export default boot(({ app, store }) => {
  const api = axios.create({ baseURL: import.meta.env.VITE_APP_API_BASE_URL });

  app.provide('axios', api);
  store.$axios = api;
});

Then on my store I have:

import { defineStore } from 'pinia';

export const useAppStore = defineStore('app', {
  state: () => ({
  }),
  getters: {
  },
  actions: {
    async login() {
      console.log(this.$axios);
      console.log('Logging in from store');
    }
  },
});

Whenever login is called it prints undefined. Any idea on what I'm doing wrong?

1 Answers

You simply have to create a Pinia plugin:

export default boot(({ app, store }) => {
  const api = axios.create({ baseURL: import.meta.env.VITE_APP_API_BASE_URL });

  app.provide('axios', api);
  store.use(() => ({ api })); // 
});
Related