In the register component after submitting the form, it shows an error like "Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'push')"
I also have a backend
Here's the code
import { Link } from "react-router-dom";
import { useState } from "react";
import { useNavigate } from 'react-router-dom'
const Register = () => {
const [userDetails, setUserDetails] = useState({
displayName: '',
email: '',
password: '',
});
const [confirmPassword, setConfirmPassword] = useState('');
const [error, setError] = useState(null);
const history = useNavigate();
const { displayName, email, password } = userDetails;
const handleRegister = async (e) => {
e.preventDefault();
if (password !== confirmPassword) {
return setError(`Passwords don't match`)
}
const response = await fetch('http://localhost:8000/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
displayName,
email,
password,
confirmPassword
})
})
const data = await response.json()
if(data.status === 'ok') {
history.push('/login');
}
console.log(data);
}
CodePudding user response:
In react router dom v6, you dont need to history.push
.
WHat you can do is: history("/login")
Not so imprtant A more relevant nomenclature will be:
const navigate = useNavigate(); //instead of history as a name
.
.
.
navigate('/login')
CodePudding user response:
I think you are confused between the Router's version,
In React Router v6,
import { useNavigate } from "react-router-dom";
function SignupForm() {
let navigate = useNavigate();
async function handleSubmit(event) {
event.preventDefault();
await submitForm(event.target);
navigate("../success", { replace: true });
}
return <form onSubmit={handleSubmit}>{/* ... */}</form>;
}
Refer: https://reactrouter.com/docs/en/v6/api#usenavigate
In React Router v5,
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}