I am making a small web application I want the user to be able to log in when they fill out the form and change the page. When the form is submitted I want my code to check whether the data inputted is correct then send the user to a different page. How am I able to do this every time I do I just get errors saying that I cant put a hook there. I have even tried putting the hook in a separate function and then calling that function if the criteria are meet and that still doesn't work
So my question is why can't they be conditions like why can i put them in an if statement and how would I be able to fix my code so I can navigate and change the page based on an if statement results.
Code
AccountSlice.tsx
const tologin = () => {
const Navigate = useNavigate();
Navigate('/Home')
}
const AccountSlice = createSlice({
name: "Account",
initialState: {ActiveAccount: [], Accounts: [{id: 1, email: "[email protected]", password: "password", isActive:false, roles: "Member"},{id: 2, email: "[email protected]", password: "password", isActive:false, roles: "Manager"}]},
reducers: {
LoginFunc : (state, action) => {
let account= state.Accounts.find((account:any)=> account.email == action.payload.email && account.password == action.payload.password)
if(account != null){
console.log("logged in")
state.ActiveAccount.pop()
state.ActiveAccount.push(account)
tologin()
}
else{
}
},
LogOut : (state, Action) => {
console.log("Logged Out")
}
}
})
export default AccountSlice.reducer;
export const { LoginFunc, LogOut} = AccountSlice.actions;
Login Component
const Login = ({onSubmit}) => {
const [Email, setEmail] = useState("")
const [Password, setPassword] = useState("")
const handleSubmit = e => {
e.preventDefault()
onSubmit(Email, Password)
}
return(
<>
<div className="Login">
<div className='Login-form'>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="firstName">First Name</label>
<input type="text" value={Email} onChange={e => setEmail(e.target.value)}/>
</div>
<div>
<label htmlFor="Password">Password</label>
<input type="password" value={Password} onChange={e => setPassword(e.target.value)}/>
</div>
<br />
<button className='form-control' type="submit">Submit</button>
</form>
</div>
</div>
</>
)
}
const mapDispatchToProps = (dispatch) => {
return{
onSubmit: (Email, Password) => {
dispatch(LoginFunc({email:Email, password:Password }));
},
};
};
export default connect(mapDispatchToProps)(Login)
State changes triggers re-renders but you can't render functions unless they are components. So hooks can only be used inside components because they encapsulate states. Instead of defining your function outside, put it inside the Login component and navigate accordingly. You can wrap you component with another component that'll automatically navigate the user according to the state changes.