How to redirect from login page if login is successful? I'm using HTTPOnly Cookie for user authentication. With the code below i'm able to redirect to home page if user logs in with their credentials. Nevertheless, if the user enters incorrect username or password, the page navigates to home page but user isn't logged in. How can I make page navigate only when credentials are correct and avoid navigating to home page if credentials are incorrect?
Login.jsx
function Login({ onUpdateUser }) {
const [formData, setFormData] = useState({
username: "",
password: "",
});
const navigate = useNavigate();
function handleChange(e) {
setFormData({ ...formData, [e.target.name]: e.target.value });
}
function handleSubmit(e) {
e.preventDefault();
fetch("http://localhost:3000/api/v1/login", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
})
.then((r) => {
if (!r.ok) throw Error("Incorrect username or password!")
.then(navigate('/login'))
})
.then((user) => onUpdateUser(user))
.then(navigate('/'))
}
if condition
part in .then
seems fishy.
I think it should be like
.then((r) => {
if (!r.ok){
throw Error("Incorrect username or password!")
}else{
// username and email are true and accepted so navigate to "/"
navigate('/')
}
})
.then((user) => onUpdateUser(user))