Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!