0

As the title says, I'm having issues with the logic of the code I wrote, it should exactly follow this pattern to authenticate a user based on the input values below:

Firstly, when the user clicks on the login button after typing in both inputs, it will call the handleAuth function which will take in username and password from the respective states, and then that function (loginCheck) will check if the user is found and matches the conditions I set in that line in, and then going to return the whole user data back to handleAuth function again, calling the last function that will navigate the user to respective pages, which are home page, in case the user is not authorized because of isLogged state is not and currentUser state is either null or undefined, or if he is authorized, and is, therefore, currentUser state is truthy and the user is found, he will be redirected to profile page, sending a username props along with..so far so good, yeah

But the thing is, it will only redirect me to the profile page when I click on the button twice, which makes the login look weird, it's obvious that I'm skipping a super important rule but can't figure it out now, feeling so stuck with that issue, any kind of help is appreciated, thanks...

I also tried replacing all functions with useEffect so it would have render only when the states get an update based on dependency arrays, but in that case i cant reach out to functions, shall i stick to useRef instead of the states?

Here you can also check the latest case live:

https://codesandbox.io/s/heuristic-mendel-syxlol?file=/src/index.js

import { Route, Routes, Link} from "react-router-dom";
import Home from "./pages/Home";
import Login from "./pages/Login";
import Profile from "./pages/Profile";
import { useNavigate } from "react-router-dom";
import { useCallback, useEffect} from 'react';
import {useState} from 'react'
import {useMemo} from  'react';

function App() {

 const [currentUser, setCurrentUser] = useState({id:null, username:null, password:null});
const [userInput, setUserInput] = useState("");
const [passInput, setPassInput] = useState("");
const [isLogged, setIsLogged] = useState(false);

  const navigate = useNavigate();

  const data = [
    { id: 1, username: "jane", password: "1234",isAdmin:true },
    { id: 2, username: "jack", password: "1234", isAdmin: false },
    { id: 3, username: "john", password: "1234" , isAdmin:false},
    { id: 4, username: "elizabeth", password: "1234", isAdmin: false}
  ];

  
  
  const loginCheck = (username, password) => {
  
    console.log("logincheck function working");
    const userData = (userid,userpass) => data.find(user => user.username === userid && user.password === userpass);  
     
       const getUserData = userData(username,password);
       console.log(getUserData)
     
       if(getUserData){
          
     console.log(`${getUserData.username} logged in`)
     return getUserData;
   
       }
       else if (getUserData===null || getUserData===undefined){
        
         console.log("user not found")
         return null
       }
       else
       {
         console.log("an error occured")
       }
     
       // eslint-disable-next-line react-hooks/exhaustive-deps
   };

const handleAuth = () => {

console.log("handlesubmit function working");
const gelen = loginCheck(userInput, passInput);

if (gelen  !== null || gelen !== undefined) {

 setIsLogged(true);
 setCurrentUser({id:gelen?.id, username:gelen?.username, password:gelen?.password});
 navigateAfterLogin();

}
else
{
setIsLogged(false);
setCurrentUser({...currentUser});
navigateAfterLogin();

}

}

const navigateAfterLogin = () => {
  console.log("navigation function working.");

  if (isLogged){
    if (currentUser.id && currentUser.username && currentUser.password) {
      console.log("redirecting to profile page");

      const timer = setTimeout(() => {
    navigate(`/users/${currentUser.username}`,
     {state: {id:currentUser.id, 
      username:currentUser.username,
     isAdmin:currentUser.isAdmin}});
      }, 3000);

      
      return () => clearTimeout(timer);

  }
}
  else {
    if (!currentUser.id && !currentUser.username && !currentUser.password) {
      console.log("redirecting to login page");
      navigate(`/login`);
    }
  
  }
};

  return (
    <div>
      <h1>Navbar</h1>
      <Link to="/">Home</Link>
      <Link to="login">Login</Link>
      <input name = "username" type = "text"  placeholder = "username" onChange={(e)=> setUserInput(e.target.value)}  /> 
      <input name = "password" type = "password"  placeholder = "password" onChange={(e)=> setPassInput(e.target.value)}/>
      <button onClick = {handleAuth} type = "submit">Login</button>
<div style = {{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center"}}>
  <h1>
<label>hesabınıza giriş yapın</label>

  </h1>
</div>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="login" element={<Login />} />
        <Route path="users/:id" element={<Profile/>} />
          
        <Route path="*" element={<h1>404 not found</h1>} />
      </Routes>
    </div>
  );
}


export default App;
berk
  • 37
  • 7
  • 1
    Don't make `isLogged` and `currentUser` states. Make them parameters of `navigateAfterLogin` and pass them directly - you're not using them anywhere else anyway. – Bergi Sep 23 '22 at 12:11
  • Alternatively, calling `navigateAfterLogin` only from an effect that depends on the `isLogged`/`currentUser` states should have worked as well – Bergi Sep 23 '22 at 12:14
  • ok never mind, fixed it now, thanks anyway, useeffect works perfectly ! – berk Sep 23 '22 at 14:46

0 Answers0