DEV Community

Zainal Shariff
Zainal Shariff

Posted on

useNavigate not working in Ternary operator

Hi guys, I'm a newbie in ReactJS and I am working on a Banking Application to get better at this library. At the moment I am stuck with a React Router problem while signing-in. To simplify my question, I have removed the JWT implementation. Basically the setAuthentication should set isAutheticated to true and then based on the ternary operator, I should be sent to "/home" and if false then the index page "/". However, every time I click on submit, I am routed to the "/" path. The router has already been set in the App.js file for both the paths mentioned. Also, when I use navigate outside of the ternary operator, it works and I am sent to the "/home" path. What could be the problem?

const [email, setEmail] = useState('')
const [password, setPassword] = useState('') 
const dispatch = useDispatch(); 
const { token, isAuthenticated } = useSelector((state) => state.userLogin) 
const navigate = useNavigate();

const handleSubmit = (e) => { e.preventDefault();
 dispatch(setAuthentication())

 isAuthenticated === true ? navigate('/home') : navigate('/');

 setEmail('');
 setPassword('')
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)