1

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('/'))
  }
1
  • I don't get it why you want to redirect user to login page if the password and username is incorrect because the user would most probably be present on login page by default Commented Sep 2, 2022 at 4:46

3 Answers 3

1

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))
0

I think you can try this

.then(()=> navigate('Home'))

instead of

.then(navigate('/login'))
-1

your use of promise... then... doesn't seem right.

.then(navigate('/login'))

should be

.then(()=> navigate('/login'))

Not the answer you're looking for? Browse other questions tagged or ask your own question.