After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code?
I am unsure if I am calling the handleLogin function correctly. Can anyone provide guidance on the proper way to do so?
function LoginForm() {
const { setAuth } = useContext<any>(AuthContext);
const [showSnackbar, setShowSnackbar] = useState(false);
const [field, setField] = useState({ username: "", password: "" });
function fieldHandler(e: any) {
setField({
...field,
[e.target.name]: e.target.value,
});
}
async function handleLogin(e: any) {
e.preventDefault();
try {
const loginReq = await axios.post(
"https://spda-api.onrender.com/api/auth/login",
{
headers: {
"Content-Type": "application/json;charset=utf-8",
},
username: field.username,
password: field.password,
}
);
const loginResp = await loginReq.data;
if (loginReq.status === 200) {
setAuth(loginResp);
Cookie.set("token", loginResp.token);
Router.push("/admin/dashboard");
}
} catch (error) {
const err = error as AxiosError;
console.log(err);
setShowSnackbar(true);
}
}
return (
<>
<section className="h-screen">
<div className="container px-6 py-12 h-full">
<div className=" md:w-8/12 lg:w-6/12 mb-12 md:mb-0">
{showSnackbar && <SnackbarAlert message="Login gagal" />}
</div>
<form>
//here is the input for username and password
<div className="mb-6">
<button
type="button"
onClick={handleLogin}
className="inline-block px-7 py-3 bg-blue-600 text-white font-medium text-sm leading-snug uppercase rounded shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out w-full"
data-mdb-ripple="true"
data-mdb-ripple-color="light"
>
Sign in
</button>
</form>
</div>
</section>
</>
);
}
export default LoginForm;
It seems that my approach to calling the function may be incorrect. Any suggestions or advice would be greatly appreciated. Thank you.