LoginFrame.tsx 1.8 KB

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