|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useState, useTransition } from 'react'; |
| 4 | +import postContact from './post-contact'; |
| 5 | +import Spinner from './spinner'; |
| 6 | + |
| 7 | +export default function Form() { |
| 8 | + const [message, setMessage] = useState(''); |
| 9 | + const [displayMessage, setDisplayMessage] = useState(false); |
| 10 | + const [isPending, startTransition] = useTransition(); |
| 11 | + |
| 12 | + const handleSubmit = (data) => { |
| 13 | + const name = data.get('name'); |
| 14 | + const email = data.get('email'); |
| 15 | + |
| 16 | + startTransition(() => { |
| 17 | + let message; |
| 18 | + |
| 19 | + postContact({ name, email }) |
| 20 | + .then(json => { |
| 21 | + console.log(`json`, json); |
| 22 | + |
| 23 | + const errorMessage = json.ErrorMessage; |
| 24 | + |
| 25 | + if (json.Count > 0) { |
| 26 | + message = 'Success! Keep an eye out on your inbox updates'; |
| 27 | + } else if (errorMessage && errorMessage.includes('already exists')) { |
| 28 | + message = 'Email is already subscribed'; |
| 29 | + } else if (errorMessage && errorMessage.includes('properties invalid')) { |
| 30 | + message = 'Email is not formatted correctly'; |
| 31 | + } else { |
| 32 | + message = 'Error. Try again or email [email protected] to be added manually.' |
| 33 | + } |
| 34 | + |
| 35 | + setMessage(message); |
| 36 | + setDisplayMessage(true); |
| 37 | + }); |
| 38 | + }); |
| 39 | + } |
| 40 | + |
| 41 | + return ( |
| 42 | + <form action={handleSubmit} className="indent grid gap-[2px] w-[270px]"> |
| 43 | + <label htmlFor="name">Name</label> |
| 44 | + <input type="text" id="name" name="name" required /> |
| 45 | + <label htmlFor="email">Email</label> |
| 46 | + <input type="email" id="email" name="email" required /> |
| 47 | + <button |
| 48 | + type="submit" |
| 49 | + disabled={isPending} |
| 50 | + className={ |
| 51 | + `bg-blue-700 text-center text-white w-[130px] h-[36px] mt-[4px] |
| 52 | + disabled:bg-slate-50 disabled:text-slate-500` |
| 53 | + } |
| 54 | + > |
| 55 | + { |
| 56 | + isPending |
| 57 | + ? ( |
| 58 | + <span className="flex justify-center items-center h-[36px]"> |
| 59 | + <Spinner /> Sending |
| 60 | + </span> |
| 61 | + ) |
| 62 | + : 'Submit' |
| 63 | + } |
| 64 | + </button> |
| 65 | + {displayMessage ? message : <></> } |
| 66 | + </form> |
| 67 | + ) |
| 68 | +} |
0 commit comments