I here want to fetch all ‘products’ using react query BUT
- ‘build process’ fails when using custom hooks inside ‘useQuery’, so it throws error in ‘build process’ but it works perfectly fine during ‘development server’
const { data, isPending, isError, error } = useQuery({ queryKey: ["products"], queryFn: ({ signal }) => useHttp({ signal }), });
(Using signal to abort http request if user navigates to other page when request is being made)
Error message shown is the below one:
Error: React Hook "useHttp" is called in function "queryFn" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".
Once again it works during development server but I’m not able to ‘build’ it due to the above error
useHttp looks like
`
export async function useHttp({ id, signal }) {
try {
const url = "https://fakestoreapi.com/products";
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error("Something went wrong");
}
const data = await response.json();
return data;
} catch (error) {
console.log(error);
}
}
`
2
Answers
According to the rules of hooks, hooks can only be called at top level in components or other hooks. You are calling the hookuseHttp
fromqueryFn
which is a violation of those rules.I can’t give you any further guidance than that without more information on
useHttp
.useHttp
is not a hook, a hook is a function that uses other hooks inside of it, whichuseHttp
doesn’t. Since it isn’t a hook, you should rename it to something that doesn’t start withuse
and then your code will compile.No, you cannot use React hooks inside the queryFn in React Query. React hooks can only be used in React function components or custom hooks that follow the rules of hooks. The queryFn is just a regular JavaScript function and doesn’t have access to the React hooks.