Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
Axios interceptors runs more than once

I have this interceptors that logs the user out if unauthorized. I do, however, get more than a 401 response, and the interceptors does therefore run for as many times as the responses I get (4). Is there a way to make it run only for the first one?

This is my code:

api.interceptors.response.use(
(response) => response,
(err) => {
  if (err.response.status === 401 && isLoggedIn) {
    api
      .delete("auth/sign_out")
      .then((resp) => {
        clearLocalStorage();
      })
      .catch((err) => {
        clearLocalStorage();
      });
  } else {
    return Promise.reject(err);
  }
  return err;
}

);

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You might want something like this to "lock out" the possible re-entrant calls:

let isLoggingOut = false; // global

// ...

api.interceptors.response.use(
  (response) => response,
  async (err) => {
    if (err.response.status === 401 && isLoggedIn) {
      if(!isLoggingOut) {
        isLoggingOut = true;  // disallow re-entrant calls
        try {
          await api.delete('auth/sign_out');
        } catch (deletionError) {
          // throw errors away
        } finally {
          clearLocalStorage();
          isLoggingOut = false;
          isLoggedIn = false; // if the variable is assignable
        }
      }
    }
    return err;
  },
);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda