How i can implement redux saga concept in login page react - reactjs

Here how can i implement this login page using Redux saga concept. I also attached my codesandbox link below. Please provide any ideas to implement using redux saga concept.
For what purpose we mainly use redux saga concepts in react. Please provide any articles for learning redux saga.
https://codesandbox.io/s/inspiring-rain-olm7wx?file=/src/components/Login.jsx
import React from "react";
import { connect } from "react-redux";
import { loginAction } from "../actions/loginAction";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
const emailValidator = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const passwordValidator = /(?=.*[a-z])/;
function Login(props) {
let navigate = useNavigate();
const isLogin = useSelector((state) => state.login.isLogin);
useEffect(() => {
if (isLogin) {
navigate("/");
}
}, [isLogin]);
const [state, setState] = useState({
email: "",
password: "",
emailAddressError: "",
passwordError: "",
isLogin: false,
isFormSubmitted: false
});
const handleChange = (event) => {
const { name, value } = event.target;
setState((prev) => ({ ...prev, [name]: value }));
return;
};
const handleBlur = (event) => {
const { name } = event.target;
validateField(name);
return;
};
const handleSubmit = (event) => {
event.preventDefault();
var data = {
email: state.email,
password: state.password
};
let formFileds = ["email", "password"];
let isValid = true;
formFileds.forEach((field) => {
isValid = validateField(field) && isValid;
});
if (isValid) {
setState((prev) => ({ ...prev, isFormSubmitted: true }));
const dispatch = props.dispatch;
dispatch(loginAction.login(data));
} else setState((prev) => ({ ...prev, isFormSubmitted: false }));
return state.isFormSubmitted;
};
const validateField = (name) => {
let isValid = false;
if (name === "email") isValid = validateemail();
else if (name === "password") isValid = validatePassword();
return isValid;
};
const validateemail = () => {
let emailAddressError = "";
const value = state.email;
if (value.trim() === "") emailAddressError = "Email Address is required";
else if (!emailValidator.test(value))
emailAddressError = "Email is not valid";
setState((prev) => ({ ...prev, emailAddressError }));
return emailAddressError === "";
};
const validatePassword = () => {
let passwordError = "";
const value = state.password;
if (value.trim() === "") passwordError = "Password is required";
else if (!passwordValidator.test(value))
passwordError = "Password contains small character only";
setState((prev) => ({ ...prev, passwordError }));
return passwordError === "";
};
return (
<div>
<div>
<div class="no-gutters row" style={{ height: "100vh" }}>
<div class="d-flex flex-column justify-content-center align-items-center h-100 col-12 col-md-6">
<div class="container">
<div class="d-flex justify-content-center row">
<div class="col-auto col-lg-8">
<h5 class="fw-bold mb-5">Login</h5>
<form className="form" onSubmit={handleSubmit}>
<div class="form-group">
<label class="form-label">
<b>Email</b>
</label>{" "}
<span style={{ color: "red" }}> *</span>
<input
type="text"
class="form-control"
label="email"
name="email"
value={state.email}
onChange={handleChange}
placeholder="email"
onBlur={handleBlur}
autoComplete="off"
/>
{state.emailAddressError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.emailAddressError}
</div>
)}
</div>
<div class="Login_formGroup__3wtgQ form-group">
<label class="form-label">
<b>Password</b>
</label>{" "}
<span style={{ color: "red" }}> *</span>
<input
type="password"
class="form-control"
variant="outlined"
id="outlined-basic"
label="password"
name="password"
value={state.password}
onChange={handleChange}
placeholder="password"
onBlur={handleBlur}
autoComplete="off"
/>
{state.passwordError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.passwordError}
</div>
)}
</div>
<div class="d-flex justify-content-between align-items-center mt-5">
<button
class="btn "
style={{ backgroundColor: "#bd744c", color: "white" }}
>
<b>LOGIN</b>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
const mapStateToProps = (state) => {
return {
token: state.login.token
};
};
export default connect(mapStateToProps)(Login);

Related

How to Validate Minimum Age Greater & Equal to 18 Reactjs

For the SignUp page I need to validate age is equal to or greater than 18. I have attempted using similar examples but all require me to install a dependency. I am looking for a way to achieve the desired results through React. My code is as follows
signup.jsx
import React from "react";
import { useState, useRef } from "react";
import { BsFillInfoCircleFill } from "react-icons/bs";
import Tooltip from "react-bootstrap/Tooltip";
import OverlayTrigger from "react-bootstrap/OverlayTrigger";
import { Link } from "react-router-dom";
import Alert from 'react-bootstrap/Alert'
import { UserAuth } from "../../AuthContext";
const Password = (props) =>
{
const [passwordShown, setPasswordShown] = useState(false);
const togglePassword = () => {
setPasswordShown(!passwordShown);
}
return(
<div className="input-group w-75 mb-5">
<input
type= {passwordShown ? 'text' : 'password'}
ref = {props.myRef}
className="form-control shadow-none"
placeholder="PSU1>OSU!"
aria-describedby="button-addon2"
></input>
<button onClick={togglePassword}>Show Password</button>
</div>
);
}
const SignUpPopup = (props) => {
//input fields
const firstName = useRef("");
const lastName = useRef("");
const email = useRef("");
const DOB = useRef("");
const password = useRef("");
const passwordConfirm = useRef("");
const [checked1, setChecked1] = useState(false);
const [checked2, setChecked2] = useState(false);
var errorMessage = ""
//change handlers
const handleChange1 = () => { setChecked1(!checked1) } ;
const handleChange2 = () => { setChecked2(!checked2) } ;
const [error, setError] = useState("");
const {createUser} = UserAuth();
//IMPROVE THE CHECKING OF THE FORM
function checkSignUp(){
var success = true
if (firstName.current.value === ""){
success = false
errorMessage += "Invalid first name\n"
}
if (lastName.current.value === ""){
success = false
errorMessage += "Invalid last name\n"
}
if (email.current.value === ""){
success = false
errorMessage += "Invalid email\n"
}
if (password.current.value === "" ){
success = false
errorMessage += "Invalid password\n"
}
if (!(passwordConfirm.current.value === password.current.value ) ){
success = false
errorMessage += "Passwords do not match\n"
}
return success;
}
async function addUserToDatabase(uid){
fetch("URL",{
method: "POST",
headers: { "Content-Type": "application/json"},
body: uid
})
}
async function handleSignup() {
setError("")
//if res == true, success, else failure and trigger alert
var res = checkSignUp();
if(res){
//authenticate
try{
await createUser(email.current.value, password.current.value);
const {user} = UserAuth();
addUserToDatabase(user.uid);
props.handleClose();
props.signupNextFunc();
}
catch(e){
errorMessage += "Invalid email or password"
setError(errorMessage)
}
}
}
const changeToLogin = ()=>{
props.handleClose()
props.loginFunc()
}
return (
<div className="popup-box">
<div className="box">
<div className="upperwrapper">
<span className="close-icon" onClick={props.handleClose}>
x
<input
type="text"
ref={firstName}
className="form-control shadow-none"
placeholder="Ben"
aria-describedby="button-addon2"
></input>
</div>
{/* LAST NAME INPUT */}
<p style={{ fontSize: "20px", marginTop: "15px" }}>
Last Name<span className="required-field"></span>
</p>
<div className="input-group w-75 mb-5">
<input
type="text"
ref = {lastName}
className="form-control shadow-none"
placeholder="Dover"
aria-describedby="button-addon2"
></input>
</div>
{/* EMAIL INPUT */}
<p style={{ fontSize: "20px", marginTop: "45px" }}>
Email<span className="required-field"></span>
</p>
<div className="input-group w-75 mb-5">
<input
type="text"
ref = {email}
className="form-control shadow-none"
placeholder="bendover#email.com"
aria-describedby="button-addon2"
></input>
</div>
<div className="d-flex bd-highlight mb-3 example-parent">
<p style={{ fontSize: "20px", marginTop: "10px" }}>
Date of Birth<span className="required-field"></span>
</p>
<div style={{ display: 'block', marginLeft: "-3px", marginTop: "-8px" }}
className="align-self-center p-2 bd-highlight col-example">
<OverlayTrigger
delay={{ hide: 450, show: 300 }}
overlay={(props) => (
<Tooltip {...props}>
Please provide your date of birth to validate...
</Tooltip>
)}
placement="right"
>
<div><BsFillInfoCircleFill /></div>
</OverlayTrigger>
</div>
</div>
<div className="input-group w-75 mb-5">
<input
type="date"
ref={DOB}
className="form-control shadow-none"
placeholder="mm/dd/yyyy"
aria-describedby="button-addon2"
></input>
</div>
)
};
export default SignUpPopup;
Any help or guidance to the right path is greatly appreciated!
You can validate age on onChange of input
const onChange = (e) => {
const currentYear = new Date().getFullYear();
const year = e.target.value.split("-")[0];
const age = currentYear - year;
if (age < 18) setError("Invalid age");
}
<input
type="date"
className="form-control shadow-none"
placeholder="mm/dd/yyyy"
aria-describedby="button-addon2"
onChange={onChange}
/>

Im facing error in firstname ,lastname required in my code. It is not showing those errors

Here for email, password and confirm password error messages are showing but for firstname, phone number and lastname the error is not showing. How can I find out what that error is?
For email when I click on that field and do not give any value, it is showing an error and the same thing for firstname.
import React from "react";
import { useState } from "react";
const emailValidator = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
function Register(props) {
const [state, setState] = useState({
email: "",
emailAddressError: "",
firstName: "",
firstNameError: ""
});
const handleChange = (event) => {
const { name, value } = event.target;
setState((prev) => ({ ...prev, [name]: value }));
return;
};
const handleBlur = (event) => {
const { name } = event.target;
validateField(name);
return;
};
const handleSubmit = (e) => {
e.preventDefault();
let formFileds = ["email", "firstName"];
let isValid = true;
formFileds.forEach((field) => {
isValid = validateField(field) && isValid;
});
if (isValid) setState((prev) => ({ ...prev, isFormSubmitted: true }));
else setState((prev) => ({ ...prev, isFormSubmitted: false }));
return state.isFormSubmitted;
};
const validateField = (name) => {
let isValid = false;
if (name === "email") isValid = validateemail();
else if (name === "firstName") isValid = validatefirstName();
return isValid;
};
const validatefirstName = () => {
let firstNameError = "";
const value = state.firstName;
if (value.trim() === "") firstNameError = "First Name is required";
setState((prev) => ({ ...prev, firstNameError }));
return firstNameError === "";
};
const validateemail = () => {
let emailAddressError = "";
const value = state.email;
if (value === "") emailAddressError = "Email Address is required";
else if (!emailValidator.test(value))
emailAddressError = "Email is not valid";
setState((prev) => ({ ...prev, emailAddressError }));
return emailAddressError === "";
};
return (
<div id="__next">
<div class="no-gutters row" style={{ height: "100vh" }}>
<div class="d-flex flex-column justify-content-center align-items-center h-100 col-12 col-md-6">
<div class="container">
<div class="d-flex justify-content-center row">
<div class="col-auto col-lg-8">
<h5 class="fw-bold mb-5">Sign Up</h5>
<form class="w-100">
<div class="d-flex form-group">
<div class="flex-fill mr-5">
<span style={{ color: "red" }}> *</span>
<label for="exampleEmail" class="fw-bold">
First Name
</label>
<input
name="firstName"
value={state.firstName}
onChange={handleChange}
maxLength="20"
class="form-control"
placeholder="First Name"
/>
</div>
{state.firstNameError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.firstNameError}
</div>
)}
</div>
<div class="form-group">
<span style={{ color: "red" }}> *</span>
<label for="exampleEmail" class="fw-bold">
Email
</label>
<input
name="email"
class="form-control"
value={state.email}
onChange={handleChange}
placeholder="Email"
onBlur={handleBlur}
autoComplete="off"
/>
</div>
{state.emailAddressError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.emailAddressError}
</div>
)}
<div class="d-flex justify-content-between align-items-center mt-5">
<a
href="/login"
style={{ textDecoration: "none", color: "#bd744c" }}
>
{" "}
</a>
<button
class="btn "
style={{ backgroundColor: "#bd744c", color: "white" }}
onSubmit={handleSubmit}
>
<b>SIGN UP</b>
</button>
</div>
</form>
<br />
</div>
</div>
</div>
</div>
<div class="d-none d-md-inline-block h-100 Register_backgroundImage__2j-eI col-sm-6"></div>
</div>
</div>
);
}
// export default Register;
export default Register;
You forgot to call onBlur={handleBlur} in firstName and I have made small changes in your code:
Now it will show errors when you click on submit.

After editing data, redux cannot read id

i have a problem.
I use a form to edit my data, then when i want to see edited data, i get an ×
TypeError: Cannot read properties of undefined (reading 'id')
Pointing at my
{users &&
users.map((user) => {
return (
<div key={user.id}>
<Link to={`users/${user.id}`}> {user.name} </Link>
</div>
);
})}
Which is used to display data.
After refreshing the site (F5) it works, so i assume that the redux has problem with reading edited data for the first time, altough it do work with adding new data. anyone know what i can do?
My UserEditForm:
const UserEditForm = () => {
let { id } = useParams();
const { user } = useSelector((state) => state.user);
const [state, setState] = useState({
name: "",
birthday: "",
img: "",
});
const [error, setError] = useState("");
console.log(id);
let history = useHistory();
let dispatch = useDispatch();
const { name, birthday, img } = state;
useEffect(() => {
dispatch(getSingleUser(id));
}, []);
useEffect(() => {
if (user) {
setState({ ...user });
}
}, [user]);
const handleInputChange = (e) => {
let { name, value } = e.target;
setState({ ...state, [name]: value });
};
const handleSubmit = (e) => {
dispatch(updateUser(state, id));
history.push("/");
setError("");
};
return (
<div>
<Button
style={{ width: "100px", marginTop: "20px" }}
variant="contained"
color="secondary"
onClick={() => history.push("/")}
>
Go Back
</Button>
<h2>Edit User</h2>
{error && <h3 style={{ color: "red" }}>{error}</h3>}
<form noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField
id="standard-basic"
label="Name"
value={name || ""}
name="name"
type="text"
onChange={handleInputChange}
/>
<br />
<TextField
id="standard-basic"
label="birthday"
name="birthday"
value={birthday || ""}
type="birthday"
onChange={handleInputChange}
/>
<br />
<TextField
id="standard-basic"
label="img"
value={img || ""}
name="img"
type="number"
onChange={handleInputChange}
/>
<Button
style={{ width: "100px" }}
variant="contained"
color="primary"
type="submit"
onChange={handleInputChange}
>
Update
</Button>
</form>
</div>
);
};
export default UserEditForm;
My UserList component:
const UserList = ({ users, history }) => {
const dispatch = useDispatch();
const fetchUsers = async () => {
const response = await axios
.get("http://localhost:3000/characters")
.catch((err) => {
console.log("Err: ", err);
});
dispatch(setUsers(response.data));
};
useEffect(() => {
fetchUsers();
}, []);
console.log(users);
return (
<div>
<button onClick={() => history.goBack()}>...back</button>
<li>
<Link to="/user/add">Add Users</Link>
</li>
{users &&
users.map((user) => {
return (
<div key={user.id}>
<Link to={`users/${user.id}`}> {user.name} </Link>
</div>
);
})}
</div>
);
};
const mapStateToProps = (state) => {
return {
users: state.allUsers.users,
};
};
export default connect(mapStateToProps, null)(UserList);

Is it possible Preload a form with Firestore values?

I have a form that uploads its values to the Firestore database, and would like to use the same component for updating the values, so the question might really be - how to load initial state according to a conditional whether the props are passed?
The form
import Servis from "./funkc/servisni";
import React, { useState } from "react";
export default function ContactUpdate(props) {
//
console.log(props.item);
//
const initialState = {
id: props.item.id,
ime: props.item.Ime,
prezime: props.item.Prezime,
imeError: "",
prezimeError: "",
date: props.item.Datum,
kontakt: props.item.Kontakt,
kontaktError: "",
published: true,
};
const [theItem, setTheItem] = useState(initialState);
const [imeError, setImeError] = useState();
const [prezimeError, setPrezimeError] = useState();
const [message, setMessage] = useState();
const { item } = props;
if (theItem.id !== item.id) {
setTheItem(item);
}
const handleInputChange = (event) => {
const { name, value } = event.target;
setTheItem({ ...theItem, [name]: value });
};
const updatePublished = (status) => {
Servis.update(theItem.id0, { published: status })
.then(() => {
setTheItem({ ...theItem, published: status });
setMessage("The status was updated successfully!");
})
.catch((e) => {
console.log(e);
});
};
const updateItem = () => {
let data = {
Ime: theItem.ime,
Prezime: theItem.prezime,
Kontakt: theItem.kontakt,
Datum: theItem.date,
published: true,
};
Servis.update(theItem.id, data)
.then(() => {
setMessage("The tutorial was updated successfully!");
})
.catch((e) => {
console.log(e);
});
};
const deleteItem = () => {
Servis.remove(theItem.id)
.then(() => {
props.refreshList();
})
.catch((e) => {
console.log(e);
});
};
const validate = () => {
let imeError = "";
let kontaktError = "";
if (!theItem.ime) {
imeError = "obavezan unos imena!";
}
if (!theItem.kontakt) {
imeError = "obavezan unos kontakta!";
}
if (kontaktError || imeError) {
this.setState({ kontaktError, imeError });
return false;
}
return true;
};
return (
<div className="container">
{theItem ? (
<div className="edit-form">
<h4>Kontakt</h4>
<form>
<div className="form-group">
<label htmlFor="ime">Ime</label>
<input
type="text"
className="form-control"
// id="title"
name="ime"
value={theItem.Ime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Prezime">Prezime</label>
<input
type="text"
className="form-control"
// id="description"
name="Prezime"
value={theItem.Prezime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Datum">Datum</label>
<input
type="text"
className="form-control"
// id="description"
name="Datum"
value={theItem.Datum}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Kontakt">Kontakt</label>
<input
type="text"
className="form-control"
// id="description"
name="Kontakt"
value={theItem.Kontakt}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label>
<strong>Status:</strong>
</label>
{theItem.published ? "Published" : "Pending"}
</div>
</form>
{theItem.published ? (
<button onClick={() => updatePublished(false)}>UnPublish</button>
) : (
<button onClick={() => updatePublished(true)}>Publish</button>
)}
<button onClick={deleteItem}>Delete</button>
<button type="submit" onClick={updateItem}>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Please click on a Tutorial...</p>
</div>
)}{" "}
</div>
);
}
The component passing the props:
import React, { useState, useEffect } from "react";
import firebase from "./firebase";
import { Link } from "react-router-dom";
export default function FireDetail({ match }) {
console.log(match);
console.log(match.params.id);
const [item, setItem] = useState([]);
const [loading, setLoading] = useState();
const getIt = () => {
setLoading(true);
const docRef = firebase
.firestore()
.collection("polja")
.doc(match.params.id)
.get()
.then((doc) => {
setItem(doc.data());
});
//
console.log(docRef);
//
// const docRef = firebase.firestore().collection("polja").doc("documentId")
//
setLoading(false);
};
useEffect(() => {
getIt();
}, [match]);
if (loading) {
return <h3>samo malo...</h3>;
}
return (
<div className="container">
<div>
{console.log("item: ", item)}
Kontakt: tip - email
<p> {item.Kontakt}</p>
</div>
<div>
<p>Datum rodjenja: {item.Datum}</p>
{item.Prezime} {item.Ime}
</div>
<Link to={`/kontakt/update/${item.id}`}> ajd </Link>
</div>
);
}
Or you might have an alternative idea on how to solve the problem?
indeed it is
export default function ContactUpdate(props) {
const initialState = {
ime: props.item.Ime,
prezime: props.item.Prezime,
datum: props.item.Datum,
kontakt: props.item.Kontakt,
id: props.Id,
};
const [theItem, setTheItem] = useState();
const [message, setMessage] = useState();
useEffect(() => {
setTheItem(props.item);
}, []);
const handleInputChange = (event) => {
const { name, value } = event.target;
setTheItem({ ...theItem, [name]: value });
console.log(theItem);
};
const updateItem = (theItem) => {
let data = {
Ime: theItem.Ime,
Prezime: theItem.Prezime,
Kontakt: theItem.Kontakt,
Datum: theItem.Datum,
};
console.log(updateItem());
Servis.update(theItem.id, data)
.then(() => {
setMessage("Uspjesno ste izmijenili unos!");
})
.catch((e) => {
console.log(e);
});
};
const deleteItem = () => {
Servis.remove(theItem.id).catch((e) => {
console.log(e);
});
};
return (
<div className="container">
{console.log(("theItem", props, theItem))}
{theItem ? (
<div className="edit-form">
<h4>Kontakt</h4>
<form>
<div className="form-group">
<label htmlFor="ime">Ime</label>
<input
type="text"
className="form-control"
name="Ime"
value={theItem.Ime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="prezime">Prezime</label>
<input
type="text"
className="form-control"
name="Prezime"
value={theItem.Prezime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="datum">Datum</label>
<input
type="text"
className="form-control"
name="Datum"
value={theItem.Datum}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="kontakt">Kontakt</label>
<input
type="text"
className="form-control"
name="Kontakt"
value={theItem.Kontakt}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label>
<strong>Status:</strong>
</label>
</div>
</form>
<button onClick={deleteItem}>Delete</button>
<button type="submit" onClick={updateItem}>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Odaberi jedan broj...</p>
</div>
)}{" "}
</div>
);
}

i want to integrate backend codes i.e. rest api to front end reactjs code

i want to integrate backend codes i.e. rest api to front end reactjs code. i have tried usingaxios . pls help i am new to react.
the code is below:
import React, { useState } from "react";
import "./Register.css";
import { useHistory } from "react-router-dom";
import axios from "axios";
function Register() {
const history = useHistory();
const [data, setData] = useState({
name: "",
phone: "",
password: "",
confirmpassword: "",
});
const [nameErr, setNameErr] = useState({});
const [phoneErr, setPhoneErr] = useState({});
const [passwordErr, setPasswordErr] = useState({});
const [confirmPasswordErr, setConfirmPasswordErr] = useState({});
const InputEvent = (event) => {
const { name, value } = event.target;
setData((preVal) => {
return {
...preVal,
[name]: value,
};
});
};
const formSubmit = (e) => {
e.preventDefault();
const isValid = formValidation();
if (isValid) {
//if form is valid, route
history.push("/myvehicles");
}
};
const formValidation = () => {
const nameErr = {};
const phoneErr = {};
const passwordErr = {};
const confirmPasswordErr = {};
let isValid = true;
if (data.name.trim().length < 4) {
nameErr.nameShort = "name is short";
isValid = false;
}
if (data.phone.trim().length < 10) {
phoneErr.phoneerror = "phone number must have 10 digits";
}
if (data.password.trim().length < 4) {
passwordErr.passwordShort = "password must be 8 characters";
isValid = false;
}
if (!(data.confirmpassword === data.password)) {
confirmPasswordErr.confirmPasswordError = "password must be same";
isValid = false;
}
setNameErr(nameErr);
setPhoneErr(phoneErr);
setPasswordErr(passwordErr);
setConfirmPasswordErr(confirmPasswordErr);
return isValid;
};
axios.post(`https://localhost:5000/`, { InputEvent }).then((res) => {
console.log(res);
console.log(res.data);
});
return (
<div className="signup__container">
<div className="signup__containerInfo">
<h1 className="h1__swari">सवारी नविकरणको लागि</h1>
<hr />
</div>
<form className="register__form" onSubmit={formSubmit}>
<h5 className="h5__form"> Name</h5>
<input
type="text"
placeholder="पुरा नाम लेख्नुहोस्"
name="name"
value={data.name}
onChange={InputEvent}
/>
{Object.keys(nameErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{nameErr[key]}
</div>
);
})}
<h5 className="h5__form"> phone </h5>
<input
type="text"
placeholder="फोन लेख्नुहोस्"
name="phone"
value={data.phone}
onChange={InputEvent}
/>
{Object.keys(phoneErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{phoneErr[key]}
</div>
);
})}
<h5 className="h5__form"> Password </h5>
<input
type="Password"
placeholder="पासवर्ड लेख्नुहोस्s"
name="password"
value={data.password}
onChange={InputEvent}
/>
{Object.keys(passwordErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{passwordErr[key]}
</div>
);
})}
<h5 className="h5__form"> Confirm Password </h5>
<input
type="Password"
placeholder="पुन: पासवर्ड लेख्नुहोस्"
name="confirmpassword"
value={data.confirmpassword}
onChange={InputEvent}
/>
{Object.keys(confirmPasswordErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{confirmPasswordErr[key]}
</div>
);
})}
<p>
<button type="submit" className="signup__registerButton">
Register Now
</button>
</p>
</form>
</div>
);
}
export default Register;
the code is as above . i want the register auth which is token based and wanted to call from the backend and the also send form values to the backend how can i do it?

Resources