Skip to content

Instantly share code, notes, and snippets.

@ryanditjia
Created August 22, 2019 16:46
Show Gist options
  • Save ryanditjia/bbf71d49a616b823a02dae3f72dce128 to your computer and use it in GitHub Desktop.
Save ryanditjia/bbf71d49a616b823a02dae3f72dce128 to your computer and use it in GitHub Desktop.
Netlify Form Submission
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