import React, { useState, useRef, useCallback } from 'react' import { useForm } from 'formhero' import axios from 'axios' import getConfig from 'next/config' const { RECAPTCHA_CLIENT } = getConfig().publicRuntimeConfig const initial = { contact: '', description: '', } const ab2str = (buf: any): string => { return String.fromCharCode.apply(null, buf); } 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(RECAPTCHA_CLIENT, { action: 'homepage' }).then(function (token) { 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