import React, { useState } from 'react' import { useCookies } from 'react-cookie' import * as Dialog from '@radix-ui/react-dialog' import api from '~utils/api' import { accountState } from '~utils/accountState' import Button from '~components/Button' import Fieldset from '~components/Fieldset' import CrossIcon from '~public/icons/Cross.svg' import './index.scss' interface Props {} interface ErrorMap { [index: string]: string email: string password: string } const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ const LoginModal = (props: Props) => { // Set up form states and error handling const [formValid, setFormValid] = useState(false) const [errors, setErrors] = useState({ email: '', password: '' }) // Cookies const [cookies, setCookies] = useCookies() // States const [open, setOpen] = useState(false) // Set up form refs const emailInput: React.RefObject = React.createRef() const passwordInput: React.RefObject = React.createRef() const form: React.RefObject[] = [emailInput, passwordInput] function handleChange(event: React.ChangeEvent) { const { name, value } = event.target let newErrors = {...errors} switch(name) { case 'email': if (value.length == 0) newErrors.email = 'Please enter your email' else if (!emailRegex.test(value)) newErrors.email = 'That email address is not valid' else newErrors.email = '' break case 'password': newErrors.password = value.length == 0 ? 'Please enter your password' : '' break default: break } setErrors(newErrors) setFormValid(validateForm(newErrors)) } function validateForm(errors: ErrorMap) { let valid = true Object.values(form).forEach( (input) => input.current?.value.length == 0 && (valid = false) ) Object.values(errors).forEach( (error) => error.length > 0 && (valid = false) ) return valid } function login(event: React.FormEvent) { event.preventDefault() const body = { email: emailInput.current?.value, password: passwordInput.current?.value, grant_type: 'password' } if (formValid) { api.login(body) .then((response) => { const cookieObj = { user_id: response.data.user.id, username: response.data.user.username, access_token: response.data.access_token } setCookies('user', cookieObj, { path: '/'}) accountState.account.authorized = true accountState.account.user = { id: cookieObj.user_id, username: cookieObj.username } setOpen(false) }, (error) => { console.error(error) }) } } function openChange(open: boolean) { setOpen(open) setErrors({ email: '', password: '' }) } return (
  • Log in
  • event.preventDefault() }>
    Log in
    ) } export default LoginModal