Home > database >  Unable to figure out cause of Invalid Hook call react error
Unable to figure out cause of Invalid Hook call react error

Time:11-25

Hi I'm building a react application and get the invalid hook call error. I've found a few posts about this error here and on other pages but none of them has helped me understand what's wrong in this case.

This is the error message

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 See >https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this >problem.

15 | if (res.ok) {
16 | setSigned_in(true); res.json().then(r => {setRole(r.role); setProfile(r);}).catch(err => alert(err));
17 | } else {
18 | setSigned_in(false); (error comes from this lien!??)
| ^ 19 | setRole(null);
20 | }
21 | })()

It's caused by a hook call from inside a custom hook

export const useLogin = () => {
    const [signed_in, setSigned_in] = useState(null);
    const [role, setRole] = useState(null);
    const [profile, setProfile] = useState(null);
    
    useEffect(() => {
        (async () => {
            const res = await fetch('/api/profile/', { method: 'GET', headers: { 'Authorization': 'Bearer '   localStorage.getItem('access_token') } });
            if (res.ok) {
                setSigned_in(true); res.json().then(r => {setRole(r.role); setProfile(r);}).catch(err => alert(err));
            } else {
                setSigned_in(false);
                setRole(null);
            }
        })()
    }, dependents);

    return {
        signed_in,
        setSigned_in,
        role,
        profile,
        setRole,
        setProfile
    }

As far as I understand this should be a valid hook call right? So it should be caused by double copies of react or mismatching versions of react and react-dom?? However I don't understand how to find out if that's the case. Running npm ls yields

├── @emotion/react@11.4.0
├── @emotion/styled@11.3.0
├── @fortawesome/fontawesome-svg-core@1.2.35
├── @fortawesome/free-solid-svg-icons@5.15.3
├── @fortawesome/react-fontawesome@0.1.14
├── @material-ui/core@5.0.0-beta.0
├── @material-ui/icons@5.0.0-beta.1
├── @material-ui/lab@5.0.0-alpha.39
├── @material-ui/styles@5.0.0-beta.1
├── @react-google-maps/api@2.2.0
├── @use-gesture/react@10.1.4
├── bindings@1.5.0 extraneous
├── bootstrap@5.0.2
├── chokidar@3.5.2
├── cra-append-sw@2.7.0
├── file-uri-to-path@1.0.0 extraneous
├── mdbreact@5.1.0
├── nan@2.14.2 extraneous
├── node-geocoder@3.27.0
├── react-dom@17.0.2
├── react-router-dom@5.2.0
├── react-scripts@4.0.2
├── react-spring@9.3.0
├── react@17.0.2
└── reactstrap@8.9.0

I can only see one react and react and react-dom are both version 17.0.2.

Does anyone know a good way to fix this issue and possibly explain how to avoid getting it again (it has appeared multiple times before and previously vanished without explanation)

CodePudding user response:

try to run this on a clean react app and see and one more thing dependents not defined

CodePudding user response:

I think this might be a red herring. For your effect hook, the dependencies should be [] instead of dependents (which is likely undefined). (There's also a missing curly brace at the end of the function.)

Does this fix it?

export const useLogin = () => {
    const [signed_in, setSigned_in] = useState(null);
    const [role, setRole] = useState(null);
    const [profile, setProfile] = useState(null);
    
    useEffect(() => {
        (async () => {
            const res = await fetch('/api/profile/', { method: 'GET', headers: { 'Authorization': 'Bearer '   localStorage.getItem('access_token') } });
            if (res.ok) {
                setSigned_in(true); res.json().then(r => {setRole(r.role); setProfile(r);}).catch(err => alert(err));
            } else {
                setSigned_in(false);
                setRole(null);
            }
        })()
    }, []);

    return {
        signed_in,
        setSigned_in,
        role,
        profile,
        setRole,
        setProfile
    }
}
  • Related