Home > Mobile >  How to redirect if login is successful?
How to redirect if login is successful?

Time:09-02

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('/'))
  }

CodePudding user response:

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

.then(navigate('/login'))

should be

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

CodePudding user response:

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

CodePudding user response:

I think you can try this

.then(()=> navigate('Home')) instead of .then(navigate('/login'))

  • Related