I am trying to set an error message for a registration form but because I am using material UI, I had to use the functional component for my project. I was following a tutorial on youtube but the guy was using a class component. I managed to convert most of the codes to a functional component but I am lost at the componentDidUpdate function.
I also tried to use useEffect function but to no avail I couldn't display the alert/message error when somebody clicks the submit button if they did not enter any fields. I also got an error that the msg is not defined in the Alert component within the SignUp component eventhough it is already defined in the useState function.
{msg ? <Alert color="danger">{msg}</Alert> : null}
Below is the code for SignUp component
import React, { useState, useEffect } from "react";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
import CssBaseline from "@material-ui/core/CssBaseline";
import TextField from "@material-ui/core/TextField";
import Link from "@material-ui/core/Link";
import Grid from "@material-ui/core/Grid";
import Box from "@material-ui/core/Box";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import Container from "@material-ui/core/Container";
import Logo from "./assets/images/logo_transparent.png";
import { Alert } from "reactstrap";
//redux
import { connect } from "react-redux";
//proptypes
import PropTypes from "prop-types";
import { register } from "./actions/authActions";
const useStyles = makeStyles(theme => ({
//styles- for brevity only
}));
function SignUp(props) {
const classes = useStyles();
const [form, setValues] = useState({
name: "",
email: "",
password: "",
msg: null
});
// Similar to componentDidMount and componentDidUpdate
//By running an empty array [] as a second argument,
//we’re letting React know that the useEffect function doesn’t
//depend on any values from props or state.
useEffect(() => {
const { error } = props;
if (error !== form.error) {
//check for register error
if (error.id === "REGISTER_FAIL") {
setValues({ msg: error.msg.msg });
} else {
setValues({ msg: null });
}
}
}, []);
const onChange = e => {
setValues({
...form,
[e.target.name]: e.target.value,
[e.target.email]: e.target.value,
[e.target.password]: e.target.value
});
};
const handleClick = e => {
e.preventDefault();
const { name, email, password } = form;
//create user object
const newUser = {
name,
email,
password
};
//attempt to register
props.register(newUser);
window.confirm("Registration details: " + name + " " + email);
//window.location.href = "http://localhost:3000/";
};
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
{msg ? <Alert color="danger">{msg}</Alert> : null}
<form className={classes.form} noValidate>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
autoComplete="name"
name="name"
variant="outlined"
required
fullWidth
id="name"
label="Full Name"
autoFocus
onChange={onChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
onChange={onChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="password"
label="Password"
type="password"
autoComplete="current-password"
onChange={onChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="cpassword"
label="Confirm Password"
type="password"
id="cpassword"
autoComplete="confirm-password"
/>
</Grid>
<Grid item xs={12} />
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={handleClick}
>
Sign Up
</Button>
<Button
href="http://localhost:3000/"
fullWidth
variant="contained"
color="primary"
className={classes.home}
>
Home
</Button>
<br />
<br />
<Grid container justify="flex-end">
<Grid item>
<Link href="http://localhost:3000/signin" variant="body2">
Already have an account? Sign in
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={5}>
</Box>
</Container>
);
}
SignUp.propTypes = {
isAuthenticated: PropTypes.bool,
error: PropTypes.object.isRequired,
register: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated,
error: state.error //getting from reducer
});
export default connect(
mapStateToProps,
{ register } //from redux actions //mapdispatchtoprop
)(SignUp); //component
This is the original componentDidUpdate function
componentDidUpdate(prevProps) {
const {error} = this.props;
if(error !== prevProps.error){
//check for register error
if(error.id === "REGISTER_FAIL"){
this.setState({msg:error.msg.msg});
}else {
setValues({ msg: null });
}
}
}
When you think of useEffect as a function that runs when a "side effect" (changing state) as componentDidUpdate is used, you need to watch out for changes in both error and msg states.
Instead of
// Similar to componentDidMount and componentDidUpdate
//By running an empty array [] as a second argument,
//we’re letting React know that the useEffect function doesn’t
//depend on any values from props or state.
useEffect(() => {
const { error } = props;
if (error !== form.error) {
//check for register error
if (error.id === "REGISTER_FAIL") {
setValues({ msg: error.msg});
} else {
setValues({ msg: null });
}
}
}, []);
You need to do
useEffect(() => {
const { error } = props;
if (error !== form.error) {
//check for register error
if (error.id === "REGISTER_FAIL") {
- setValues(({ msg: error.msg});
+ setValues({ ...form, msg: error.msg});
} else {
- setValues({ msg: null });
+ setValues({ ...form, msg: null });
}
}
}, [error, form.msg]);
The reason I am spreading ...form like setValues({ ...form, msg: error.msg.msg }) is because an updator function (2nd argument) returned by React.useState does not update other properties in the state.
So setValues({ msg: null }); would turn form from
{
name: 'previous name',
password: 'previous password',
email: 'previous email',
msg: 'previous message...'
}
into {msg: null} removing name, email, password properties.
As the behavior between React.useState's updator ("aliased" as setState in React documentation) and setState is different someone ended up creating use-legay-state NPM package, which you probably shouldn't be using unless absolutely necessary.
Unrelated to your question, you'd also want to either
1. separate name/email/password/msg into separate states
2. "or" use useReducer hook.
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
Should you want to keep using an object form, you might want to follow a convention of naming by changing setValues to setForm or const [formValues, setFormValues] = useState({...}).
And you can update each field like,
<TextField
autoComplete="name"
name="name"
variant="outlined"
required
fullWidth
id="name"
label="Full Name"
autoFocus
value={name}
onChange={e => setName(e.target.value)}
/>
You can use useCallback for onChange like onChange={useCallback(e => setName(e.target.value), [name])} here but not necessary unless you have a performance issue. Start simple initially 😉
And also it'd make your useEffect to depend on msg only.
useEffect(() => {
const { error } = props;
if (error !== form.error) {
//check for register error
if (error.id === "REGISTER_FAIL") {
setMessage(error.msg);
} else {
setMessage(null);
}
}
}, [error, message]);
Here I changed setValues to setMessage and dependency array from [error, form] to [error, message].
If you want to use useReducer, it seems like more work as you are changing indivisual form field, which are changed separately. useReducer works better when you update a related set of states that should change together. But in your case, each state (password/name etc) change independently as user input so it'd be easier to get started with case #1 above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With