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 Hook "useNavigate" cannot be called in a class component

I would like to know how I can go to another view after my axios answer.

import axios from "axios";
import {useNavigate} from "react-router-dom";

export class EmployeeNetworking {
    async authentication(email: string, password: string) {
        const navigate = useNavigate();
        await axios.post("http://localhost:3000/login", {
            email: email,
            password: password
        }).then(response => {
            console.log(response)
            navigate("/dashboard")
        }).catch(errors => {
            console.log(errors)
        })
    }
}

Line 6:26: React Hook "useNavigate" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function

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 :

As one comment mentioned, take a look to the react documentation.

"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".

But as I can see, you can create a custom hook to achieve what you want.

import axios from "axios";
import {useNavigate} from "react-router-dom";

const useEmployeeNetworking = () => {
    const navigate = useNavigate();

    const handleAuth = async (email: string, password: string) => {
        await axios.post("http://localhost:3000/login", {
            email: email,
            password: password
        }).then(response => {
            console.log(response)
            navigate("/dashboard")
        }).catch(errors => {
            console.log(errors)
        });
    }

 return { handleAuth }
}

In this way you could use it as the following example:


const = Container() => {
  const { useAuth } = useEmployeeNetworking();
  //restOfThecode...
  return (...);
}

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