import React, { useReducer, useState, useEffect } from "react";
const emailReducer = (state, action) => {
if (action.type === "USER_INPUT") {
return { value: action.val, isValid: action.val.length > 5 ? true : false };
}
if (action.type === "INPUT_BLUR") {
return {
value: state.value,
isValid: state.value.length > 5 ? true : false,
};
}
return { value: "", isValid: false };
};
const passwordReducer = (state, action) => {
if (action.type === "PASS_IP") {
return {
value: action.value,
isValid: action.value.length > 5 ? true : false,
};
} else if (action.type === "PASS_BLUR") {
return {
value: state.value,
isValid: state.value.length > 5 ? true : false,
};
} else {
return { value: "", isValid: null };
}
};
const Login = () => {
const [formIsValid, setFormIsValid] = useState(false);
const [emailState, dispatchEmail] = useReducer(emailReducer, {
value: "",
isValid: null,
});
const [passState, dispatchpass] = useReducer(passwordReducer, {
value: "",
isValid: null,
});
//---------
useEffect(() => {
console.log("EFFECT RUNNING");
return () => {
console.log("EFFECT CLEANUP");
};
}, []);
const { isValid: emailIsValid } = emailState;
const { isValid: passwordIsValid } = passState;
useEffect(() => {
const identifier = setTimeout(() => {
console.log("Checking form validity!");
setFormIsValid(emailIsValid && passwordIsValid);
}, 500);
return () => {
console.log("CLEANUP");
clearTimeout(identifier);
};
}, [emailIsValid, passwordIsValid]);
//---------------
const emailChangeHandler = (event) => {
dispatchEmail({ type: "USER_INPUT", val: event.target.value });
console.log("dis em");
};
const validateEmailHandler = () => {
dispatchEmail({ type: "INPUT_BLUR" });
};
const passwordHandler = (event) => {
dispatchpass({ type: "PASS_IP", value: event.target.value });
};
const passwordBlurHandler = () => {
dispatchpass({ type: "PASS_BLUR" });
};
const submitHandler = (event) => {
event.preventDefault();
// props.onLogin(emailState.value, enteredPassword);
};
return (
<form onSubmit={submitHandler}>
email:{emailState.isValid}
pass:{passState.isValid}
<div>
{emailState.value}
<label htmlFor="email">E-Mail</label>
<input
style={{ color: emailState.isValid ? "" : "red" }}
type="email"
id="email"
value={emailState.value}
onChange={emailChangeHandler}
onBlur={validateEmailHandler}
/>
</div>
<input
type="password"
value={passState.value}
onChange={passwordHandler}
onBlur={passwordBlurHandler}
/>
<button type="submit" disabled={!formIsValid}>
submit
</button>
</form>
);
};
export default Login;
No comments:
Post a Comment