React Hooks must be called in a React function component or a custom React Hook function

Viewed 13251

I am trying to write an error handler, but I get this error: React Hook "useHttpErrorHandler" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function I don't how else can I handle this errorHandler.

this is withErrorHandler :

    const WithErrorHandler = (WrappedComponent, axios) => {
        return props => {
            const [error, clearError] = useHttpErrorHandler(axios);
            return (
                <div>
                    <ErrorModal show={error} errorModalClosed={clearError}>
                        {error ? error.message : null}
                    </ErrorModal>
                    <WrappedComponent {...props}/>
                </div>
            )
        }
    };
    
    export default WithErrorHandler;

and this is http-error-handler:

export default httpClient => {
    const [error, setError] = useState(null);

    const reqInterceptor = httpClient.interceptors.request.use(req => {
        setError(null);
        return req;
    });
    const resInterceptor = httpClient.interceptors.response.use(
        res => res,
        err => {
            setError(err);
        }
    );
    useEffect(() => {
        return () => {
            httpClient.interceptors.request.eject(reqInterceptor);
            httpClient.interceptors.response.eject(resInterceptor);
        };
    }, [reqInterceptor, resInterceptor])
    const errorConfirmHandler = () => {
        setError(null);
    };

    return [error, errorConfirmHandler]
}
3 Answers

I stumbled upon the same error message when I was using a hook in a useEffect. Might be a bit unrelated to the OP question, but I'm pretty sure you will come here when you google the error message.

So, what you can do is use a ref to your hook function.

  const { hookFunction } = useMyHook();
  const hookFunctionRef = useRef(hookFunction);

Then use the hookFunctionRef.current() in your useEffect and the hookFunctionRef in your useEffect dependency array.

I just stumbled upon same problem for what solved it, is to put your use effect within the main function where the return is called but not within the return it self nor outside the main function.

    function Navbar() {
    useEffect(() => {........}
    return ()
}

You cannot use the hook within a return statement, try below, keeping the hook outside of return:

  const WithErrorHandler = (WrappedComponent, axios) => {
    const [error, clearError] = useHttpErrorHandler(axios);
    return props => {
      return (
        <div>
          <ErrorModal show={error} errorModalClosed={clearError}>
            {error ? error.message : null}
          </ErrorModal>
          <WrappedComponent {...props} />
        </div>
      );
    };
  };
Related