I created a register page, in which I have the inputs email, password, first name, and last name. Upon clicking the "Register" button, I received an error message that says "TypeError: Cannot read properties of undefined (reading ‘data’) at handleClick". What is the problem here?
Below is my code:
import { useState } from "react";
import "./register.scss";
import axios from "axios";
const Register = () => {
const [inputs, setInputs] = useState({
email: "",
password: "",
firstName: "",
lastName: "",
});
const [err, setErr] = useState(null);
const handleChange = (e) => {
setInputs(prev => ({...prev, [e.target.name]: e.target.value}));
};
const handleClick = async e => {
e.preventDefault();
try{
await axios.post("http://localhost:8800/api/auth/register", inputs);
} catch (err) {
setErr(err.response.data);
}
};
console.log(err);
return (
<div className="register-page">
<form>
<input type="email" placeholder="Email" name="email" onChange={handleChange} />
<input type="password" placeholder="Enter Password" name="password" onChange={handleChange} />
<input type="text" placeholder="First Name" name="firstName" onChange={handleChange} />
<input type="text" placeholder="Last Name" name="lastName" onChange={handleChange} />
{err && err}
<button onClick={handleClick}>Register</button>
</form>
</div>
)
};
export default Register;
If everything works normally, I should be able to see the email, password, first name, and last name posted onto the backend server table on MySQL.
2
Answers
Seems like the code falls into the catch statement and
is undefined. Try to
console.log(err)
to see if the structure of the error you get is the expected one.I have checked your component with my own API, that answers with code 200 to the request. And there is no mistake in react component code. Everything works fine with working server.
The net::ERR_CONNECTION_REFUSED response indicates that there is an error with connection to server. Please check the connection.
And you can modify your error handler with something like it:
setErr(err && err.response ? err.response.data : err)
;or
setErr(err.response?.data)
;