简体   繁体   中英

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

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.

Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns.

See Rules of Hooks for more.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM