Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
How to use hooks inside non React component?

I'm really new to react and I have this

import Axios from "axios";
import { useAuth } from "react-oidc-context";

const ProductService = {
    getProductList: () => {
        return Axios({
            method: "get",
            url: "<myurl>",
            headers: {
                "Authorization": useAuth().user?.access_token
            }
        }).then((response) => {
            return response.data;
        }).catch((error) => {
            console.log(error);
        });
    },
    getProduct: (productId: string) => {
        return Axios({
            method: "get",
            url: "<myurl>/" + productId,
            headers: {
                "Authorization": useAuth().user?.access_token
            }
        }).then((response) => {
            return response.data;
        }).catch((error) => {
            console.log(error);
        });
    },
    addClient: (data: any) => {
        return Axios({
            method: "post",
            url: "<myurl>",
            data: data,
            headers: {
                "Authorization": useAuth().user?.access_token
            }
        }).then((response) => {
            return response.data;
        }).catch((error) => {
            console.log(error);
        });
    }
}

export default ProductService  

Notice that I'm trying to use useAuth() in the Authorization header and I'm getting React Hook "useAuth" is called in function "getProductList" which is neither a React function component or a custom React Hook function.

In this case, what's the workaround so I can use useAuth() to get user token.

My Component

<Button type="submit"
          onClick={() => {
            ProductService.addClient(data)
              .then(() => {
                toggleModal();
              });
          }}>
          Add
        </Button>

Thanks

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Hooks is a function that controls state management or life cycle methods of the React component through registered order. So, React Hooks are not available outside the component. Please refer to the Link.

Only Call Hooks at the Top Level. So, the getProductList should be changed as follows.

const getProductList = (access_token) => {
  if (!access_token) throw new Error('No access_token');
  return Axios({
    method: "get",
    url: "<myurl>",
    headers: {
      "Authorization": access_token
    }
  }).then((response) => {
    return response.data;
  }).catch((error) => {
    console.log(error);
  });
};

const YourReactComponent = () => {
  const auth = useAuth();
  
  useEffect(() => {
    getProductList(auth?.user?.access_token)
      .then(() => {
        /* NEXT STEP */
      })
  }, [auth?.user?.access_token]);

  return <>
    Component Text.
  </>
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

As per Hooks rule, we can use hooks only from React function components or custom Hooks.

In your scenario,

  1. Create one React component.
  2. Get value from "useAuth()" in above functional component.
  3. Pass above the value to ProductService.getProductList(auth) as one of the parameter.

I hope you are calling ProductService from particular react component right. Get auth value from there and pass it to ProductService.getProductList(auth)

const ProductService = {
    getProductList: (authToken: any) => {
        return Axios({
            method: "get",
            url: "<myurl>",
            headers: {
                "Authorization": authToken
            }
        }).then((response) => {
            return response.data;
        }).catch((error) => {
            console.log(error);
        });
    },
    getProduct: (authToken: any, productId: string) => {
        return Axios({
            method: "get",
            url: "<myurl>/" + productId,
            headers: {
                "Authorization": authToken
            }
        }).then((response) => {
            return response.data;
        }).catch((error) => {
            console.log(error);
        });
    },
    addClient: (authToken: any, data: any) => {
        return Axios({
            method: "post",
            url: "<myurl>",
            data: data,
            headers: {
                "Authorization": authToken
            }
        }).then((response) => {
            return response.data;
        }).catch((error) => {
            console.log(error);
        });
    }
}

const TestReactFunctionalComponent = () => {
  const auth = useAuth();
  
  // use below calling wherever you want inside this component
  ProductService.getProductList(auth.user?.access_token);

  return(
   // your compoent elements
  ) 
};

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda