This repository has been archived by the owner on Nov 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
newsletter-improved.js
113 lines (100 loc) · 2.62 KB
/
newsletter-improved.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const useNewsletter = () => {
const [loading, setLoading] = useState(false)
const [apiError, setApiError] = useState(false)
const sendNewsletter = () => {
try {
setLoading(true)
const response = await fetch('/api/newsletter', { method: 'POST', body: { name, email } })
if(!response.ok) {
setApiError(true)
}
} catch (error) {
console.error('[Newsletter]:', error.message)
setApiError(true)
} finally {
setLoading(false)
}
}
return [sendNewsletter, { apiError, loading }]
}
const Newsletter = () => {
const [name, setName] = useState('')
const [nameError, setNameError] = useState(null)
const [nameTouched, setNameTouched] = useState(false)
const [email, setEmail] = useState('')
const [emailError, setEmailError] = useState(null)
const [emailTouched, setEmailTouched] = useState(false)
const [sendNewsletter, { apiError }] = useNewsletter()
const clearForm = () => {
setName('')
setEmail('')
}
const isEmailValid = (email) => (
!email.match(/^[a-z0-9.]+@[a-z0-9]+\.[a-z]+\.([a-z]+)?$/i)
)
const validateEmail = (email) => {
if(isEmailValid(email)) {
setEmailError(new Error('invalid email'))
} else {
setEmailError(null)
}
}
const handleNameChange = ({ currentTarget }) => {
const newName = currentTarget.value
if(!newName.length) {
setNameError(new Error('invalid name'))
} else {
setNameError(null)
}
setApiError(false)
setName(newName)
}
const handleEmailChange = ({ currentTarget }) => {
const newEmail = currentTarget.email
validateEmail()
setApiError(false)
setEmail(newEmail)
}
const handleNameBlur = () => {
setNameTouched(true)
}
const handleEmailBlur = () => {
setEmailTouched(true)
}
const handleSubmit = async () => {
clearForm()
setNameTouched(true)
setEmailTouched(true)
sendNewsletter()
}
return (
<>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Nombre"
value={name}
onBlur={handleNameBlur}
onChange={handleNameChange}
/>
{nameTouched && nameError && (
<span>Invalid name!</span>
)}
<input
type="email"
placeholder="Email"
value={email}
onBlur={handleEmailBlur}
onChange={handleEmailChange}
/>
{emailTouched && emailError && (
<span>Invalid name!</span>
)}
<button type="submit">Enviar</button>
</form>
{apiError && (
<p>Hubo un error. Inténtalo de nuevo</p>
)}
</>
)
}