skip to Main Content

I here want to fetch all ‘products’ using react query BUT

  1. ‘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


  1. According to the rules of hooks, hooks can only be called at top level in components or other hooks. You are calling the hook useHttp from queryFn 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, which useHttp doesn’t. Since it isn’t a hook, you should rename it to something that doesn’t start with use and then your code will compile.

    Login or Signup to reply.
  2. 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.

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