import { useFormState } from "react-use-form-state"; import React, { useEffect, useState } from "react"; import { Flex } from "reflexbox/styled-components"; import emailValidator from "email-validator"; import styled from "styled-components"; import Router from "next/router"; import Link from "next/link"; import axios from "axios"; import { useStoreState, useStoreActions } from "../store"; import { ColCenterV } from "../components/Layout"; import AppWrapper from "../components/AppWrapper"; import { TextInput } from "../components/Input"; import { fadeIn } from "../helpers/animations"; import { Button } from "../components/Button"; import Text, { H2 } from "../components/Text"; import ALink from "../components/ALink"; import Icon from "../components/Icon"; import { API } from "../consts"; const LoginForm = styled(Flex).attrs({ as: "form", flexDirection: "column" })` animation: ${fadeIn} 0.8s ease-out; `; const Email = styled.span` font-weight: normal; color: #512da8; border-bottom: 1px dotted #999; `; const LoginPage = () => { const { isAuthenticated } = useStoreState(s => s.auth); const login = useStoreActions(s => s.auth.login); const [error, setError] = useState(""); const [verifying, setVerifying] = useState(false); const [loading, setLoading] = useState({ login: false, signup: false }); const [formState, { email, password, label }] = useFormState<{ email: string; password: string; }>(null, { withIds: true }); useEffect(() => { if (isAuthenticated) Router.push("/"); }, [isAuthenticated]); function onSubmit(type: "login" | "signup") { return async e => { e.preventDefault(); const { email, password } = formState.values; if (loading.login || loading.signup) return null; if (!email) { return setError("Email address must not be empty."); } if (!emailValidator.validate(email)) { return setError("Email address is not valid."); } if (password.trim().length < 8) { return setError("Password must be at least 8 chars long."); } setError(""); if (type === "login") { setLoading(s => ({ ...s, login: true })); try { await login(formState.values); Router.push("/"); } catch (error) { setError(error.response.data.error); } } if (type === "signup") { setLoading(s => ({ ...s, signup: true })); try { await axios.post(API.SIGNUP, { email, password }); setVerifying(true); } catch (error) { setError(error.response.data.error); } } setLoading({ login: false, signup: false }); }; } if (isAuthenticated) { return null; } return ( {verifying ? (

A verification email has been sent to{" "} {formState.values.email}.

) : ( Email address: Password (min chars: 8): Forgot your password? {error} )}
); }; export default LoginPage;