Skip to content

Instantly share code, notes, and snippets.

@dueka
Created August 4, 2021 06:07
Show Gist options
  • Save dueka/a23c1e64b24900879d0f24c7727bf69c to your computer and use it in GitHub Desktop.
Save dueka/a23c1e64b24900879d0f24c7727bf69c to your computer and use it in GitHub Desktop.
Login form.
import React, { useState } from "react";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import InputField from "../../components/InputField";
import "./Login.scss";
import { withRouter, Link } from "react-router-dom";
import { useDispatch } from "react-redux";
import { setUser } from "../../redux/ducks/user";
import axios from "axios";
import Cookies from "js-cookie";
const LoginForm = ({ history }) => {
const dispatch = useDispatch();
const [isLoading, setLoading] = useState(false);
const [errors, setErrors] = useState([]);
const handleSubmit = (values, { resetForm }) => {
setLoading(true);
setErrors([]);
axios
.post(`${process.env.REACT_APP_API}/login`, values)
.then((res) => {
setLoading(false);
// empty inputs
resetForm(values);
// set token in header
axios.defaults.headers.common["authorization"] = res.data.data.token;
//set token in Cookie
Cookies.set("token", res.data.data.token);
Cookies.set("isAuthenticated", true);
//set user and accounts in redux store
dispatch(setUser(res.data.data.user));
// redirect to dashboard
history.replace("/");
// reload page to dispatch user accounts
window.location.reload();
})
.catch((err) => {
setLoading(false);
console.log(err);
//add errors to error
const apiErrors = err.response.data.errors;
const errorsArr = [];
for (const property in apiErrors) {
errorsArr.push(apiErrors[property][0]);
}
setErrors([...errorsArr]);
});
};
const validate = Yup.object({
email: Yup.string().email().required("Email is required"),
password: Yup.string().required("Password is required"),
});
return (
<div className="text-left form-container">
{errors.length > 0 && (
<div className="alert alert-danger login-alert" role="alert">
{errors.map((error, index) => (
<p key={index} style={{ fontSize: "14px" }}>
{error}
</p>
))}
</div>
)}
<Formik
initialValues={{
email: "",
password: "",
}}
validationSchema={validate}
onSubmit={handleSubmit}
>
{(formik) => (
<Form>
<InputField
label="EMAIL ADDRESS"
name="email"
type="email"
placeholder="EMAIL ADDRESS"
/>
<InputField
label="ENTER YOUR PASSWORD"
name="password"
type="password"
placeholder="********"
/>
<p className="forget-pass">
<Link to="/forget-password">Forgot password?</Link>
</p>
<button
type="submit"
className="btn btn-primary mt-2 login-btn"
disabled={isLoading}
>
{isLoading ? "Please wait..." : "Login"}
</button>
</Form>
)}
</Formik>
<p className="text-center py-4 reg-bottom-text">
Don't have an account?
<span className="text-primary ml-1">
<Link to="/register">Register</Link>
</span>
</p>
</div>
);
};
export default withRouter(LoginForm);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment