import React, { useState, useCallback } from 'react' import { useForm } from 'formhero' const initial = { contact: '', description: '', } const Form: React.FC = () => { const [loading, setLoading] = useState(false) const [message, setMessage] = useState({ title: '', error: false, }) const { field, form, setForm } = useForm(initial) const [files, setFiles] = useState([] as File[]) const _onFileChange = useCallback( async (e: React.ChangeEvent) => { setMessage({ title: '', error: false }) const uploaded = Array.from(e.target.files || []) const nonAudio = uploaded.find((file) => !/^audio\//.test(file.type)) if (nonAudio) { setMessage({ title: `Error: ${nonAudio.name} You can only select audio files.`, error: true, }) return } setFiles([...files, ...uploaded]) }, [files] ) const _clear = useCallback(() => { setFiles([]) }, []) const _submit = useCallback( (e: React.FormEvent) => { e.preventDefault() if (loading) return // @ts-ignore window.grecaptcha.ready(() => { // @ts-ignore window.grecaptcha .execute(process.env.NEXT_PUBLIC_RECAPTCHA_CLIENT, { action: 'homepage' }) .then(function (token: string) { setLoading(true) setMessage({ title: '', error: false }) const body = new FormData() body.append( 'json', JSON.stringify({ ...form, token, }) ) for (const file of files) { body.append(file.name, file) } fetch('/api/form', { method: 'POST', body, }) .then(() => { setForm(initial) setFiles([]) setMessage({ title: 'Uploaded 🚀', error: false }) }) .catch(() => setMessage({ title: 'Something went wrong 😥', error: true })) .finally(() => setLoading(false)) }) }) }, [form, files, loading] ) return (

submit track