The spinner is not setting to false when I put it on Email Validation in axios .post() inside. My objective is show a loading spinner only when a http request is called and set to false when data returned from Axios API. However, the spinner loading is keep going even after. I have put the isLoading as a default of false. When user clicks submit, the axios request is processing and triggers a setIsLoading of isLoading to true and setIsLoading to false in .then().
What I've tried conditional is
.post(
"https://xkode.herokuapp.com/api/user",
userObj,
regexEmail.test(userObj.user) ? setIsLoading(true) : null
)
and My actual structure:
import React, { useState } from "react";
import "./style.scss";
import { message, Spin } from "antd";
import axios from "axios";
const LoginForm = () => {
const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = (e) => {
const regexEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
e.preventDefault();
const userObj = {
user: userName.trim().toLowerCase(),
password: password.trim(),
};
setIsLoading(true);
axios
.post(
"https://xkode.herokuapp.com/api/user",
userObj,
regexEmail.test(userObj.user) ? setIsLoading(true) : null
)
.then((response) => {
console.log(response.data);
setIsLoading(false);
if (response.data.success === 1) {
message.success("Login Successful.");
}
if (response.data.success === 0) {
message.error("Check username and password.");
}
})
.catch((error) => {
console.log(error);
});
};
return (
<div className="container" style=>
<div className="loginForm leftSection">
<div>
<h1>Sign in to Login Module</h1>
</div>
</div>
<div className="loginForm rightSection">
<form onSubmit={(e) => handleSubmit(e)}>
<h2>Login</h2>
<label>Username</label>
<input
type="text"
placeholder="Enter Username"
value={userName}
onChange={(e) => setUserName(e.target.value)}
/>
<label>Password</label>
<input
type="text"
placeholder="Enter Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
{isLoading === true ? (
<Spin medium />
) : (
<input type="submit" value="Submit" />
)}
</form>
</div>
</div>
);
};
export default LoginForm;
Any idea(s) what I'm doing wrong?
Aucun commentaire:
Enregistrer un commentaire