Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Please save the returned id and eject with that as the parameter. #6219

Open
homocodian opened this issue Feb 5, 2024 · 1 comment
Open

Comments

@homocodian
Copy link

          Please save the returned id and `eject` with that as the parameter.
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

Originally posted by @chinesedfan in #2615 (comment)

@homocodian
Copy link
Author

homocodian commented Feb 5, 2024

import { Capacitor } from "@capacitor/core";
import axios from "axios";

const axiosInstance = axios.create({
  baseURL: Capacitor.isNativePlatform()
    ? import.meta.env.VITE_BASE_URL_FOR_CAPACITOR
    : import.meta.env.VITE_BASE_URL,
  timeout: 25000,
});

function getInterceptor(token: string) {
  return axiosInstance.interceptors.request.use(
    (config) => {
      config.headers.Authorization = `Bearer ${token}`;
      return config;
    },

    (error) => {
      return Promise.reject(error);
    },
  );
}

function destroyInterceptor(interceptor: number) {
  axiosInstance.interceptors.request.eject(interceptor);
}

export { axiosInstance, destroyInterceptor, getInterceptor };

and this is how I use

async function fetchSomething(
  uid: string | null | undefined,
  token: string | null,
) {
  if (!uid || !token) {
    return Promise.reject("Invalid token");
  }
  const searchParams = new URLSearchParams();
  searchParams.set("user", uid);

  const interceptor = getInterceptor(token);
  const res = await axiosInstance.get(`/notes?${searchParams.toString()}`);
  console.log(axiosInstance.interceptors);
  destroyInterceptor(interceptor);
  console.log(axiosInstance.interceptors);
  return res.data;
}

does not remove interceptor just keeps on adding in every request

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant