Home > Software design >  React: Button link to another page
React: Button link to another page

Time:11-01

I have a login page and the backend and frontend are ready all data to connect together, but my problem is: I wanna click on login button and then redirect to another page! i know how i have to redirect to another page with useNavigate, but the main problem is: if username and password is correct, then has to be link to another page! not automatically connecting when button onclick is!

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>



import React, {useState} from "react";
import {NavLink, useNavigate} from "react-router-dom";
import axios from "axios";
import "./LoginPage.css"

export default function LoginPage() {

    const [username, setUsername] = useState("")
    const [password, setPassword] = useState("")
    const [me, setMe] = useState("")

    const navigate = useNavigate();

    function handleLogin(){
        axios.get("api/user/login",{auth: {username, password}})
            .then(response => response.data)
            .then((data) => setMe(data))
            .then(() => setUsername(""))
            .then(() => setPassword(""))
            .catch(() => alert("Sorry, Username or Password is wrong or Empty!"))
           
    }

    function handleLogout(){
        axios.get("api/user/logout")
            .then(() => setMe(""))
    }



    return (
      <div className={"login-main"}>

            <NavLink to={"/question"}>zur Question Page</NavLink>
            <h1>Login Page</h1>

                    <h3>Login</h3>
                    <input placeholder={"Username ..."} value={username} onChange={event => setUsername(event.target.value)}/>
                    <input placeholder={"Password ..."} type={"password"} value={password} onChange={event => setPassword(event.target.value)}/>
                    <button onClick={() => {
                        handleLogin();
                        {navigate("/question")}
                    }}>Login</button>
          
            }

      </div>


          )
}

!

CodePudding user response:

Move navigate("/question") inside of the handleLogin function. In there you need to have a check of is this a good login name and password? If so then you can navigate. I would make handlelogin an async function that awaits the result. If it is a good result then you can move to the login, if not then you could give the user an error message. Where it is currently written in the onclick function, it has no knowledge of the login method, so it has nothing to wait for, so it executes as soon as you click.

Edit: I would also suggest adding validations to the input fields. That way you can disable the button from the user, so they can't even click the button if the input fields are not valid.

var loginSuccessful = false;
  const handleLogin = async () => {
    // create an async/await function to make the db call

    await axios.get("api/user/login",{auth: {username, password}}).then((response) => { // wait for api call
      setPost(response.data);
      setUsername("");
      setPassword("");
      loginSuccessful = true; // set login to true or false based on result
    }).catch(error => {
      console.log(error);
      loginSuccessful = false;
    });

    // create a boolean check if the login was successful or not. You need to make the api call to login, 
    // that api call will return with an ok response or an error response

    // if the api call returned with a 200 response then it was successful and you can navigate
    // if you have the navigate not wrapped with an if check then it will still route whenever it gets here
    // so this check is very important
    if (loginSuccessful) { 
      navigate("/question")
    } else {
      // if the api call returned with some other 400-500 ish reponse then it failed and you can display an error message
    } 
}

If you just move the navigate to the function, then it will have the same result. You need to wait for the api call to finish, and then based on the response you get, you can choose to login or not. If the response is a bad response then display an error. If the response is good, then you can navigate.

CodePudding user response:

You could have handleClick() return a Boolean value to determine whether or not a login was successful:

function handleLogin(){
  let success;

  axios.get("api/user/login",{auth: {username, password}})
    .then(response => response.data)
    .then((data) => {
      setMe(data);
      success = true;
    })
    .then(() => setUsername(""))
    .then(() => setPassword(""))
    .catch(() => {
      alert("Sorry, Username or Password is wrong or Empty!");
      success = false ;
    });

  return success;      
}

Then you could tie this in to a ternary operator to conditionally pass a string to navigate():

navigate(handleClick() ? '/question' : '/someOtherComponent');

Hope this helps.

  • Related