sweetalert pop up if passwords don't match - reactjs

I want to make good pop up to my project with sweetalert when the passwords don't match:
const SignUp = ({ signUpStart, userError, resetError }) => {
const [userCredentials, setUserCredentials] = useState({
displayName: "",
email: "",
password: "",
confirmPassword: "",
});
const { displayName, email, password, confirmPassword } = userCredentials;
const handleSubmit = async (event) => {
event.preventDefault();
if (password !== confirmPassword) {
alert(`password don't match`);
return;
}
signUpStart({ displayName, email, password });
};
const handleChange = (event) => {
const { name, value } = event.target;
setUserCredentials({ ...userCredentials, [name]: value });
};
return (
<div className="signup">
<h2 className="title">I do not have a account</h2>
<span>Sign up with your email </span>
<form className="sign-up-form" onSubmit={handleSubmit}>
<Form
type="text"
name="displayName"
value={displayName}
onChange={handleChange}
label="Display Name"
required
></Form>
<Form
type="email"
name="email"
value={email}
onChange={handleChange}
label="Email"
required
></Form>
<Form
type="password"
name="password"
value={password}
onChange={handleChange}
label="Password"
required
></Form>
<Form
type="password"
name="confirmPassword"
value={confirmPassword}
onChange={handleChange}
label="Confirm Password"
required
></Form>
<CustomButton type="submit">SIGN UP</CustomButton>
</form>
{userError && userError.message ? (
<SweetAlert
show={!!userError.message}
type="warning"
title="Something went wrong"
text={userError.message}
onConfirm={() => resetError()}
/>
) : null}
</div>
);
};
EDIT: i add my whole component to the question. i deleted my mapstatetoprops and dispatch.
So i basically want to run once when i hit my submit button.
I want to make the alert in the if statement. But I think I need to refactor little. Can anyone help with this?

Related

useDispatch stops render of the page

I'm using React, redux with typescript to build a frontend page. In one of the page, I want to register a user. I utilized useDispatch() and the page stops rendering. If I comment out the useDispatch() line, the page will render normally.
I can't find anything online regarding this.
const Register: FC<any> = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
password2: '',
})
// If I comment out this line, the page will render normally
const dispatch = useDispatch<any>()
const { name, email, password, password2 } = formData
const onSubmit = (e: any) => {
e.preventDefault()
if (password !== password2) {
toast.error('Passwords do not match')
} else {
const userData = {
name,
email,
password,
}
dispatch(register(userData))
}
}
const onChange = (e: any) => {
setFormData((prevState) => ({
...prevState,
[e.target.name]: e.target.value,
}))
}
return (
<>
<section className='heading'>
<h1>
<SlUserFollowing /> Register
</h1>
<p>Please create an account</p >
</section>
<section className='form'>
<form onSubmit={onSubmit}>
<div className='form-group'>
<input
type='text'
className='form-control'
id='name'
name='name'
value={name}
onChange={onChange}
placeholder='Enter your name'
required
/>
</div>
<div className='form-group'>
<input
type='email'
className='form-control'
id='email'
name='email'
value={email}
onChange={onChange}
placeholder='Enter your email'
required
/>
</div>
<div className='form-group'>
<input
type='password'
className='form-control'
id='password'
name='password'
value={password}
onChange={onChange}
placeholder='Enter password'
required
/>
</div>
<div className='form-group'>
<input
type='password'
className='form-control'
id='password2'
name='password2'
value={password2}
onChange={onChange}
placeholder='Confirm password'
required
/>
</div>
<div className='form-group'>
<button className='btn btn-block'>Submit</button>
</div>
</form>
</section>
</>
);
};
export default Register;
I searched online and didn't find any source regarding this.

How to display an Error message when logging in fails in Reactjs

How to display an Error message when logging in fails in Reactjs.
I want to display the alert message 'Invalid Username or Password, Please try again.' when the user logs in fails on the page. How can I do that in Reactjs?
the code:
login.js
export default function LogIn() {
let history = useHistory();
const initialFormData = Object.freeze({
username: '',
password: '',
});
const [formData, updateFormData] = useState(initialFormData);
const handleChange = (e) => {
updateFormData({
...formData,
[e.target.name]: e.target.value.trim(),
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
axiosInstance
.post(`token/`, {
username: formData.username,
password: formData.password,
})
.then((res) => {
localStorage.setItem('access_token', res.data.access);
localStorage.setItem('refresh_token', res.data.refresh);
axiosInstance.defaults.headers['Authorization'] =
'JWT ' + localStorage.getItem('access_token');
history.push("/home");
});
};
return (
<Box component="form" onSubmit={handleSubmit} noValidate>
<TextField
margin="normal"
required
id="username"
label="username"
name="username"
autoComplete="username"
autoFocus
onChange={handleChange}/>
<TextField
margin="normal"
required
name="password"
label="password"
type="password"
id="password"
autoComplete="current-password"
onChange={handleChange}/>
<Button type="submit" onClick={handleSubmit}>
LOG IN
</Button>
</Box>
);}
Thank you in advance.
you can use alert in javascript to show a dialog box also you can use this Pakage
to show alert or message to the user
you can use this code to set error in state and show in label
const [error,setError]=useState();
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
axiosInstance
.post(`token/`, {
username: formData.username,
password: formData.password,
})
.then((res) => {
localStorage.setItem('access_token', res.data.access);
localStorage.setItem('refresh_token', res.data.refresh);
axiosInstance.defaults.headers['Authorization'] =
'JWT ' + localStorage.getItem('access_token');
history.push("/home");
}, reason => {
console.error(reason); // Error!
setError('Invalid Username or Password')
});
};
return (
<Box component="form" onSubmit={handleSubmit} noValidate>
<TextField
margin="normal"
required
id="username"
label="username"
name="username"
autoComplete="username"
autoFocus
onChange={handleChange}/>
<TextField
margin="normal"
required
name="password"
label="password"
type="password"
id="password"
autoComplete="current-password"
onChange={handleChange}/>
<Button type="submit" onClick={handleSubmit}>
LOG IN
</Button>
{error?<Label>{error}</Label>:null}
</Box>
);

Why I can't fill anything in my form in React?

So I have a form, and I need users to fill this form and when they send a message, it should come to my gmail. I use EmailJS service for this.
So my form looks like this:
So as you see, users can send me messages, and my code looks like this:
Usestate for sending data:
const [toSend, setToSend] = useState({
from_name: '',
to_name: '',
message: '',
reply_to: '',
subject: ''
});
onSubmit function:
const onSubmit = (e) => {
e.preventDefault();
send(
'service_id',
'template_id',
toSend,
'user_id'
)
.then((response) => {
console.log('SUCCESS!', response.status, response.text);
})
.catch((err) => {
console.log('FAILED...', err);
});
reset();
};
handleChange function:
const handleChange = (e) => {
setToSend({ ...toSend, [e.target.name]: e.target.value });
};
useform hook:
const {register, handleSubmit, formState: { errors }, reset, trigger} = useForm();
Whole form:
<form onSubmit={handleSubmit(onSubmit)}>
<input type="text"
placeholder="Name"
name="from_name"
value={toSend.from_name}
onChange={handleChange}
id="name" {...register('name', { required: "Name is required" })}
onKeyUp={() => {
trigger("name");
}}/>
{errors.name && (<span className="danger_text">{errors.name.message}</span>)}
<input type="text"
placeholder="Email"
name="reply_to"
value={toSend.reply_to}
onChange={handleChange}
id="email" {...register("email", { required: "Email is Required" ,
pattern: {
value: /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: "Invalid email address",
}})}
onKeyUp={() => {
trigger("email");
}}
/>
{errors.email && (
<small className="danger_text">{errors.email.message}</small>
)}
<input type="text"
placeholder=
"Subject"
id="subj"
name="subject"
value={toSend.subject}
onChange={handleChange}/>
<input type="text"
placeholder="Message"
id="msg"
name="message"
value={toSend.message}
onChange={handleChange}
{...register('msg', { required: true })}/>
{errors.msg && (<small className="danger_text">Enter your message</small>)}
<input type="submit" className="btn_red" value="Send a message"></input>
</form>
So my problem is that I can't fill anything in inputs. When I try to type something it just doesn't type in, I'm guessing it has something to do with "value=.." in all inputs, but I'm not sure what's exactly the problem here.
You don't need to define onChnage, value, onKeyUp on your inputs, when you call register on input, it returns onChange,onBlur,ref, then react-hook-forms will control the values by ref. so below example should solve your problem:
import { useForm } from 'react-hook-form';
...
function MyComp() {
const {
register,
handleSubmit,
formState: { errors },
reset,
} = useForm();
const onSubmit = (toSend) => {
send(
'service_id',
'template_id',
toSend,
'user_id'
)
.then((response) => {
console.log('SUCCESS!', response.status, response.text);
})
.catch((err) => {
console.log('FAILED...', err);
});
reset();
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
type="text"
placeholder="Name"
name="from_name"
id="name"
{...register('from_name', { required: 'Name is required' })}
/>
{errors.from_name && (
<span className="danger_text">{errors.from_name.message}</span>
)}
<input
type="text"
placeholder="Email"
name="reply_to"
id="email"
{...register('reply_to', {
required: 'Email is Required',
pattern: {
value: /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: 'Invalid email address',
},
})}
/>
{errors.reply_to && (
<small className="danger_text">{errors.reply_to.message}</small>
)}
<input
type="text"
placeholder="Subject"
id="subj"
name="subject"
{...register('subject')}
/>
<input
type="text"
placeholder="Message"
id="msg"
name="message"
{...register('message', { required: true })}
/>
{errors.message && <small className="danger_text">Enter your message</small>}
<input type="submit" className="btn_red" value="Send a message"></input>
</form>
);
}
BTW, consider that register works with input's name, not id.

How to change Input fields values in React?

I am not being able to change input fields.Any suggestion?
const MiddlePanel = ({ user }) => {
const history = useHistory();
const [data, setData] = useState({
firstname: '',
lastname: '',
email: '',
phoneNo: '',
});
const { firstname, lastname, email, phoneNo } = data;
useEffect(() => {
const fetchUser = async () => {
const res = await axios.get(`http://localhost:5000/users/${user._id}`);
setData({
firstname: res.data.firstname,
lastname: res.data.lastname,
email: res.data.email,
password: res.data.password,
});
};
fetchUser();
}, [user._id]);
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
const newUser = { firstname, lastname, email, phoneNo };
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const body = JSON.stringify(newUser);
await axios.patch(
`http://localhost:5000/users/${user._id}`,
body,
config
);
history.push("/");
} catch (err) {}
};
return (
<div>
<Form onSubmit={handleSubmit}>
<Input
type="text"
name="firstname"
onChange={handleChange}
value={user.firstname}
/>
<Input
type="text"
name="lastname"
onChange={handleChange}
value={user.lastname}
/>
<Input
type="email"
name="email"
onChange={handleChange}
value={user.email}
/>
<Input
type="tel"
name="phoneNo"
onChange={handleChange}
value={user.phoneNo}
/>
<PrimaryButton className="btn btn-primary" style={{ width: "100%" }}>
Update
</PrimaryButton>
</Form>
</div>
);
};
I think you should use data.firstname instead of user for the value property
<div>
<Form onSubmit={handleSubmit}>
<Input
type="text"
name="firstname"
onChange={handleChange}
value={data.firstname}
/>
<Input
type="text"
name="lastname"
onChange={handleChange}
value={data.lastname}
/>
<Input
type="email"
name="email"
onChange={handleChange}
value={data.email}
/>
<Input
type="tel"
name="phoneNo"
onChange={handleChange}
value={data.phoneNo}
/>
<PrimaryButton className="btn btn-primary" style={{ width: "100%" }}>
Update
</PrimaryButton>
</Form>
</div>

onchange in a form using formik the value of the field is not updated

I'm new to react, and I'm trying to apply validations to a form.
For some reason when adding the property:
onChange={onChange}
I want to send the values to the parent component. That's why I'm using the onchange.
Nothing I write is shown in my text fields, why does this happen?
export const Son = props => {
const { onChange } = props;
return (
<Formik
initialValues={{
fullname: "",
email: ""
}}
validationSchema={Yup.object().shape({
fullname: Yup.string()
.min(2, "Your name is too short")
.required("Please enter your full name"),
email: Yup.string()
.email("The email is incorrect")
.required("Please enter your email")
})}
onSubmit={(values, { setSubmitting }) => {
const timeOut = setTimeout(() => {
console.log(values);
setSubmitting(false);
clearTimeout(timeOut);
}, 1000);
}}
>
{({
values,
errors,
touched,
handleSubmit,
isSubmitting,
validating,
valid
}) => {
return (
<Form name="contact" method="post" onSubmit={handleSubmit}>
<label htmlFor="fullname">
Fullname
<Field
type="text"
name="fullname"
autoComplete="name"
placeholder="your fullname"
onChange={onChange}
/>
</label>
{<ErrorMessage name="fullname">{msg => <p>{msg}</p>}</ErrorMessage>}
{/*errors.fullname && touched.fullname && <p>{errors.fullname}</p>*/}
<br />
<label htmlFor="email">
Email
<Field
type="email"
name="email"
autoComplete="email"
placeholder="your email"
onChange={onChange}
/>
</label>
<ErrorMessage name="email">{msg => <p>{msg}</p>}</ErrorMessage>
<br />
<button type="submit" disabled={!valid || isSubmitting}>
{isSubmitting ? `Submiting...` : `Submit`}
</button>
</Form>
);
}}
</Formik>
);
};
this is my live code:
https://stackblitz.com/edit/react-qotvwb?file=components/son_component.js
you're not using the formik handleChange at all.
I highlighted the changes that I made in https://stackblitz.com/
and you can test this working here

Resources