skip to Main Content

I have a api file that I would like to store all my api calls and use react query to call those api function, however I have some endpoint which are private and I use a custom hooks for that logic. Issue is I cannot call the custom hook in the api file as it is not a functional component? How do I handle this

//api file

import useAxiosPrivate from "../hooks/useAxiosPrivate";

export const GetPackagesinfo = async () => {
const axiosPrivate = useAxiosPrivate();
const res = await axiosPrivate.get(
"/mk_get_packages_information"
);
return res.data;
};

 export const GetAccountInfo = async () => {
const axiosPrivate = useAxiosPrivate();
const res = await axiosPrivate.get(
"/mk_company_admin_user_account_information"
);
return res.data;
};

export const DeleteAcccount = async () => {
const axiosPrivate = useAxiosPrivate();
const res = await axiosPrivate.delete(
"/mk_company_admin_user_delete_account_information"
);
  return res.data;
  };

if i try to use as above i get the 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

3

Answers


  1. Chosen as BEST ANSWER

    I did not find any alternative so I just copypasted each api function to its target component/page and used it from there and i was able to use my hooks as intended


  2. In short, you can’t (as the warning mentions).

    I don’t know what is in useAxiosPrivate, but you can extract the non-React parts of that into its own non-hook function. Then both api.js and useAxiosPrivate.js can import the non-hook function.

    Login or Signup to reply.
  3. You can’t use hooks in react-query ‘s queryFn.

    While react-query will apply your function inside like:

    useSyncExternalStore(
      useCallback(
        ()=>{
          useAxiosPrivate()
        },[]
    ),
    ()=>{}
    )
    

    enter image description here

    It break the rules of React hooks.
    See https://reactjs.org/warnings/invalid-hook-call-warning.html#breaking-the-rules-of-hooks

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search