0

I am currently rewriting my website into a webapp with ReactJS, and have a little trouble using and understanding hooks. I wrote a custom hook "useFetch" that works, never had any problems with it until now : I am currently trying to use my hook in a function like this :

import useFetch from '../../../hooks/useFetch';
import {clientGenerateProcessScreen, clientClearProcessScreen} from '../../../utils/processScreens';

function myFunction (paramName, paramType, paramDesc) {
    let process_screen = clientGenerateProcessScreen ();
    let rqt_url = `/fileNameA.php`;
    if (paramType!= "a") rqt_url = `/fileNameB.php`;

    const { data, isLoading, error } = useFetch(rqt_url);
    if (!isLoading && data.success) {
        doSomethingA ();
    } else {
        showErrorMessage ();
    }
}
export default myFunction;

The function is called from an onClick on a react component. It should theorically work fine, however, I always end up having this error :

Uncaught 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

I do not understand where the error here is. I am using my hook at the top of a function, not in a condition or anything that might break hook rules. I have tried importing React and ReactDOM in my function file, but this doesn't solve any of my issues. I am guessing I might have missed something basic or simple, yet can't find what...

  • 1
    You don't give any context or a reproducible example to allow fixing suggestions. See [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Dennis Vash Dec 19 '21 at 10:16
  • You can't call a hook in a callback (like an onClick event handler). You can either call a hook in component, or in another hook. You'll have to reorganize your code around these rules. – Balázs Édes Dec 19 '21 at 10:25

1 Answers1

1

Firstly, you implemented a custom hook, therefore it should be prefixed with the "use" word: useMyFunction, for more context see Do React hooks really have to start with "use"?.

Now that you know its a hook and not a util function, it must follow hooks API ("Rules of Hooks"), and one of those rules is that you must call it in a top level, i.e You CANT use it as a callback.

For solving it, it requires a logical change, its not something you have a step-by-step fixing guide, rethink its logical use.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • Thank ! My hook is prefixed with "use", but as you said the issue here is that i can't use in a callback. Thanks for pointing that out and have a great day ! :) – Dita Tavares Dec 19 '21 at 10:36