LoginFrame.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /** @jsx h */
  2. import { h } from "preact";
  3. import { useState, useEffect } from "preact/hooks";
  4. import { showLoading, hideLoading } from "utils/ui.ts";
  5. export default function LoginFrame() {
  6. const [email, setEmail] = useState("");
  7. const [password, setPassword] = useState("");
  8. const [emailError, setEmailError] = useState(false);
  9. const [passwordError, setPasswordError] = useState(false);
  10. const checkUserLogin = async () => {
  11. const resp = await fetch("/api/user/login");
  12. const respJson = await resp.json();
  13. if (respJson.success) {
  14. // Redirect to main page if valid
  15. location.href = "/";
  16. return true;
  17. }
  18. return false;
  19. };
  20. const doUserLogin = async () => {
  21. const resp = await fetch("/api/user/login", {
  22. method: "POST",
  23. headers: { "Content-Type": "application/json" },
  24. body: JSON.stringify({
  25. email,
  26. password,
  27. }),
  28. });
  29. const respJson = await resp.json();
  30. if (respJson.success) {
  31. location.href = "/";
  32. return true;
  33. }
  34. return false;
  35. };
  36. useEffect(() => {
  37. checkUserLogin();
  38. }, []);
  39. const onSubmit = async () => {
  40. showLoading();
  41. if (email && password) {
  42. await doUserLogin();
  43. }
  44. // Set error
  45. if (!email) {
  46. setEmailError(true);
  47. }
  48. if (!password) {
  49. setPasswordError(true);
  50. }
  51. hideLoading();
  52. };
  53. return (
  54. <div className="pd-login-frame">
  55. <span className="pd-login-input-label">Email</span>
  56. <input
  57. className={`pd-login-input${emailError ? " error" : ""}`}
  58. type="text"
  59. placeholder="Your email"
  60. value={email}
  61. onInput={(e) => {
  62. setEmailError(false);
  63. setEmail((e.target as HTMLInputElement).value);
  64. }}
  65. />
  66. <span className="pd-login-input-label">Password</span>
  67. <input
  68. className={`pd-login-input${passwordError ? " error" : ""}`}
  69. type="password"
  70. placeholder="Your password"
  71. value={password}
  72. onInput={(e) => {
  73. setPasswordError(false);
  74. setPassword((e.target as HTMLInputElement).value);
  75. }}
  76. />
  77. <button className="pd-login-btn" type="button" onClick={onSubmit}>
  78. Sign in
  79. </button>
  80. </div>
  81. );
  82. }