I can't pass the navigation response to the next page after the user correctly fills in the password and email.
I tried passing the navigate from the useNavigation library instead of the answer but when I go to fill in the password or email it doesn't check if the fields are right.
How could I put in place of the response a navigate but checking if the data is right in the database?
import "../App.css";
import * as yup from "yup";
import { ErrorMessage, Formik, Form, Field } from "formik";
import Axios from "axios";
import { useNavigate } from "react-router-dom";
const Login = () => {
// const navigate = useNavigate();
const handleLogin = (values) => {
Axios.post("http://localhost:3001/login", {
email: values.email,
password: values.password,
}).then((response) => {
alert(response.data);
// navigate("/Home")
// console.log(response);
});
};
const validationsLogin = yup.object().shape({
email: yup
.string()
.email("email inválido")
.required("O email é obrigatório"),
password: yup
.string()
.min(8, "A senha deve ter pelo menos 8 caracteres")
.required("A senha é obrigatória"),
});
return (
<div className="container">
<h1>Login</h1>
<Formik
initialValues={{}}
onSubmit={handleLogin}
validationSchema={validationsLogin}
>
<Form className="login-form">
<div className="login-form-group">
<Field name="email" className="form-field" placeholder="Email" />
<ErrorMessage
component="span"
name="email"
className="form-error"
/>
</div>
{/*Outro campo*/}
<div className="form-group">
<Field name="password" className="form-field" placeholder="Senha" />
<ErrorMessage
component="span"
name="password"
className="form-error"
/>
</div>
<button className="button" type="submit">
Login
</button>
</Form>
</Formik>
</div>
);
};
export default Login;
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "bd_login_cadastro",
});
app.use(express.json());
app.use(cors());
app.post("/register", (req, res) => {
const email = req.body.email;
const password = req.body.password;
db.query("SELECT * FROM usuarios WHERE email = ?", [email], (err, result) => {
if (err) {
res.send(err);
}
if (result.length == 0) {
bcrypt.hash(password, saltRounds, (err, hash) => {
db.query(
"INSERT INTO usuarios (email, password) VALUE (?,?)",
[email, hash],
(error, response) => {
if (err) {
res.send(err);
}
res.send({ msg: "Usuário cadastrado com sucesso" });
}
);
});
} else {
res.send({ msg: "Email já cadastrado" });
}
});
});
app.post("/login", (req, res) => {
const email = req.body.email;
const password = req.body.password;
db.query("SELECT * FROM usuarios WHERE email = ?", [email], (err, result) => {
if (err) {
res.send(err);
}
if (result.length > 0) {
bcrypt.compare(password, result[0].password, (error, response) => {
if (error) {
res.send(error);
}
if (response) {
res.send({ msg: "Usuário logado" });
} else {
res.send({ msg: "Senha incorreta" });
}
});
} else {
res.send({ msg: "Usuário não registrado!" });
}
});
});