Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React, getting Error: Invalid hook call. Hooks can only be called inside of the body of a function component

Can anyone help me with React Hooks basics, I am relatively new and couldn’t find proper help online

import React from 'react'
import { auth, provider } from "../../../firebaseSetup";
import { useNavigate } from "react-router-dom"


const GoogleAuth = async() => {
  const navigate = useNavigate()

    auth.signInWithPopup(provider).then(() => {
      navigate('/home');
    }).catch((error) => {
      console.log(error.message)
    })
}
export  default GoogleAuth

I get error on const navigate = useNavigate() saying:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What they want for useNavigate (and all hooks) is to be called only at the top level of a React component or a custom hook. A solution to your problem could be calling const navigate = useNavigate() in the component where you will use GoogleAuth, and pass navigate as parameter. As an example like so:

import React from 'react'
import { auth, provider } from "../../../firebaseSetup";
import { useNavigate } from "react-router-dom"


const GoogleAuth = async(navigate) => {
    auth.signInWithPopup(provider).then(() => {
      navigate('/home');
    }).catch((error) => {
      console.log(error.message)
    })
}
export  default GoogleAuth
import GoogleAuth from "GoogleAuth";
const App = ()=>{
       /* 
          here at the top level, not inside an if block,
          not inside a function defined here in the component...
       */
       const navigate = useNavigate(); 
       useEffect(()=>{
         GoogleAuth(navigate)
       },[])
       return <div></div>
    }
export default App;

To learn more about it, you could see the official documentation here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading