summary refs log tree commit diff
path: root/components/ContactForm.tsx
blob: a64cb858f7165b14cc4b8fbcc01e078b8b49b556 (plain)
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
'use client'

import styles from '~/styles/form.module.css'

const submitUrl = 'https://contact.tempest.dev/api/contact/me'
import { useState, useRef, FormEvent } from 'react'

export default function ContactForm() {
  const [submitting, setSubmitting] = useState(false)
  const [status, setStatus] = useState('')

  const nameRef = useRef<HTMLInputElement>()
  const emailRef = useRef<HTMLInputElement>()
  const messageRef = useRef<HTMLTextAreaElement>()

  const submit = async (ev: FormEvent<HTMLFormElement>) => {
    ev.preventDefault()

    setStatus('')

    const name = nameRef.current.value
    const email = emailRef.current.value
    const message = messageRef.current.value

    if (!name) setStatus(s => s + ' Name required.')
    if (!email) setStatus(s => s + ' Email required.')
    if (!message) setStatus(s => s + ' Message required.')

    if (!name || !email || !message)
      return

    setSubmitting(true)

    try {

      await fetch(submitUrl, {
        method: 'post',
        headers: {
          'content-type': 'application/json'
        },
        body: JSON.stringify({
          name, email, message
        })
      })

      setStatus('Message sent successfully')
    } catch {
      setStatus('Error submitting message, please try again')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <form className={styles.form} onSubmit={submit}>
      <label htmlFor="name">Name:</label>
      <input disabled={submitting} name="name" ref={nameRef} />

      <label htmlFor="email">Email:</label>
      <input disabled={submitting} name="email" ref={emailRef} />

      <label htmlFor="message">Message:</label>
      <textarea disabled={submitting} name="message" ref={messageRef} />

      <button disabled={submitting} type="submit">Submit</button>
      {status && <span className={styles.status}>{status}</span>}
    </form>
  )
}