Home > Back-end >  axois react-keycloak/web token in inteceptor
axois react-keycloak/web token in inteceptor

Time:11-07

I am 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?

CodePudding user response:

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 />;
}
  • Related