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
CodePudding user response:
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 (...);
}