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

253
Visualizações
axois react-keycloak/web token in inteceptor

I'm trying to use a request inteceptor with react-keycloak/web - however i get an array of errors when doing so.

import axios from 'axios';
import { useKeycloak } from '@react-keycloak/web';

const { keycloak } = useKeycloak();

const instance = axios.create({
  baseURL: 'https://example.com/api/v1/',
  timeout: 30000,
});

instance.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `${keycloak.token}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

but i get:

React Hook "useKeycloak" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks

Now i have of course tried to create a function with for example GetToken():

function GetToken() {
  const { keycloak } = useKeycloak();
  return keycloak.token
}

but doing so leaves me with:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

What am i doing wrong here?

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

0

You can't use react hooks out of react tree.

You can export axoios instance and import it elsewhere inside react (eg: App.js) and set interceptors there.

for example:

import axiosIns from 'api';
import { useKeycloak } from '@react-keycloak/web';
import { useEffect } from "react";
import WholeApp from "WholeApp";

const App = () => {
    const { keycloak } = useKeycloak();

    useEffect(() => {
        axiosIns.interceptors.request.use(
            (config) => {
                config.headers.Authorization = `${keycloak.token}`;
                return config;
            },
            (error) => {
                return Promise.reject(error);
            }
        );
    }, []);

    return <WholeApp />;
}
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