I am doing a login, and I need that when I enter the wrong password or the email I get an error message but I do not know how to do it, I am working with the POST method and also in nextjs
this is my code:
function Login({}) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
useEffect(() => {
if (localStorage.getItem("user-info")) {
}
}, []);
async function login() {
console.warn(email, password);
let item = { email, password };
let result = await fetch(
"https://login-test.repl.co/auth/login",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(item),
}
);
result = await result.json();
localStorage.setItem("user-info", JSON.stringify(result));
}
return (
<div className="bg-white w-full rounded-lg shadow p-2 h-screen flex justify-center items-center relative">
<div className="w-full ">
<input
id="inputEmail"
onChange={(e) => setEmail(e.target.value)}
type="email"
/>
<input
id="inputPassword"
onChange={(e) => setPassword(e.target.value)}
type="password"
/>
<button type="submit" onClick={login}>
Login
</button>
<div className={`${!error ? "hidden" : ""}`}>
INCORRECT PASSWORD OR EMAIL
</div>
</div>
</div>
);
}
export default Login;
when I put the wrong password or the mail they send me this:
CodePudding user response:
Can you check like this
function Login({}) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState(null);
useEffect(() => {
if (localStorage.getItem("user-info")) {
}
}, []);
async function login() {
setError(false);
console.warn(email, password);
let item = { email, password };
try {
let result = await fetch(
"https://login-test.repl.co/auth/login",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(item),
}
);
result = await result.json();
localStorage.setItem("user-info", JSON.stringify(result));
} catch(error) {
setError(true);
}
}
return (
<div className="bg-white w-full rounded-lg shadow p-2 h-screen flex justify-center items-center relative">
<div className="w-full ">
<input
id="inputEmail"
onChange={(e) => setEmail(e.target.value)}
type="email"
/>
<input
id="inputPassword"
onChange={(e) => setPassword(e.target.value)}
type="password"
/>
<button type="submit" onClick={login}>
Login
</button>
<div className={`${!error ? "hidden" : ""}`}>
INCORRECT PASSWORD OR EMAIL
</div>
</div>
</div>
);
}
export default Login;
CodePudding user response:
You can acheieve this by checking the status code.
If you are getting status of 200 then u can update the state like
if(result.status === 200)
{
setEmail("Email Already Exists");
}
You can get more status code and u can set the errors as u like.