Created
August 22, 2019 16:46
-
-
Save ryanditjia/bbf71d49a616b823a02dae3f72dce128 to your computer and use it in GitHub Desktop.
Netlify Form Submission
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface BaseFormData { | |
'form-name': string | |
} | |
type FormDataWithFile = BaseFormData & Record<string, string | File> | |
type FormDataWithoutFile = BaseFormData & Record<string, string> | |
/* | |
* Encoding forms with attachments (input type file) | |
*/ | |
function encodeWithFile(data: FormDataWithFile): FormData { | |
const formData = new FormData() | |
Object.entries(data).forEach(([key, value]) => { | |
formData.append(key, value) | |
}) | |
return formData | |
} | |
/* | |
* Encoding forms without attachments | |
*/ | |
function encodeWithoutFile(data: FormDataWithoutFile): string { | |
return Object.entries(data) | |
.map( | |
([key, value]) => | |
encodeURIComponent(key) + '=' + encodeURIComponent(value), | |
) | |
.join('&') | |
} | |
/* | |
* AJAX Netlify Forms submission | |
*/ | |
export async function postFormToNetlify( | |
data: FormDataWithFile | FormDataWithoutFile, | |
) { | |
const hasFile = Object.values(data).some(value => value instanceof File) | |
await fetch('/', { | |
method: 'POST', | |
...(hasFile && { | |
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, | |
}), | |
body: hasFile | |
? encodeWithFile(data) | |
: encodeWithoutFile(data as FormDataWithoutFile), // how do I type-guard this? | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment