So i create a login page with a button to sign and hit API. but when i click the button, it doesn't do anything. is there any mistake in my code? i checked console log it didn't show any error or response.
how can i call the handleLogin function in a right way?
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;
i think the way i call the function is wrong. anyone have a suggestion? thank you.
CodePudding user response:
The only thing I see here type="button"
<button
type="submit"
>
Sign in
</button>
when type is set as submit
, form data is sent to the form handler. since type is "button" there is no communication between form handler and button
CodePudding user response:
Since you are using TS, you should type the e
parameter of handleLogin
:
async function handleLogin(e: React.SyntheticEvent) { ... }
Then, add the onSubmit
event to the form
tag and make the button
of type submit
, removing its onClick
event:
<form onSubmit="handleLogin">
//here is the input for username and password
<div className="mb-6">
<button
type="submit"
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>