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
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
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.You can’t use hooks in react-query ‘s queryFn.
While react-query will apply your function inside like:
It break the rules of React hooks.
See https://reactjs.org/warnings/invalid-hook-call-warning.html#breaking-the-rules-of-hooks