0

the issue is quite clear, i want my useEffect hook to trigger only when the dependency arrays change because of my code's logic, not at the initial render, in which the page loads for first time, but as you can also see from the codes below, it just shows the message saying "unsuccessful login" on the middle of the page even though user doesnt yet type any input and submit it...i just want it to show the successful message only when user credentials are correct, whats wrong with my code, any help is highly appreciated.

i know it sounds weird authenticating users at client side but thats just a simple simulation of how it would work only in react...

you can check the finalized version of the code here to get a better understanding:

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 [error, setError] = useState("");

  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`)
     console.log(currentUser)
     return getUserData;
   
       }
       else if (getUserData===null || getUserData===undefined){
        
         console.log("user not found")
         console.log(currentUser)
         return null
       }
       else
       {
        console.log(currentUser)
         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});
 console.log(currentUser)
 console.log(isLogged)

}
else
{
setIsLogged(false);
setCurrentUser({id:null, username:null, password:null});
console.log(currentUser)
 console.log(isLogged)


}

}

useEffect(() => {
  console.log("useeffect working")
  
  if (isLogged){
    if (currentUser.id && currentUser.username && currentUser.password) {
      console.log("redirecting to profile page");
      console.log("login successful")
      
      const timer = setTimeout(() => {
    navigate(`/users/${currentUser.username}`,
     {state: {id:currentUser.id, 
      username:currentUser.username,
     isAdmin:currentUser.isAdmin}});
      }, 3000);

      return () => clearTimeout(timer);

  }
}
  else {
    
    setError("login unsuccessful");
    console.log("login unsuccessful")
  
  }  
}
// eslint-disable-next-line react-hooks/exhaustive-deps
, [currentUser]);

  return (
    <div>
      
      <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><br/>
<div>

{isLogged ? <h1 style = {{color:"green"}}>login successful</h1> : 
<h1 style = {{color:"red"}}>{error}</h1>}


</div>
  
 

</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;

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
berk
  • 37
  • 7
  • This is how React hooks work. It's intended behavior for them to be called each and every render cycle. The `useEffect` hook callback is ***guaranteed*** to be called ***at least*** once on the initial render. Any time after that will depend on dependencies. Are you wanting to [skip the side-effect on the initial render](/a/53180013/8690857)? Or maybe an `useEffect` hook isn't quite the best place for this auth check logic? – Drew Reese Sep 23 '22 at 19:33
  • Welcome to Stack Overflow! This is not a website where people write code for you so that you don't have to. If you need help debugging code that you have written, you must post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and explain the specific problem with your code. – romellem Sep 23 '22 at 19:38

0 Answers0