Last active
November 23, 2022 07:05
-
-
Save yingray/58ca6280e38ad5e717126e00f28d23d0 to your computer and use it in GitHub Desktop.
Form submit in Typescript
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
type TFormSubmitOptions = { | |
body?: { [key: string]: any }; | |
method?: string; | |
}; | |
const formSubmit = (endpoint: string, options?: TFormSubmitOptions) => { | |
const { body = {}, method = 'POST' } = options || {}; | |
const form = document.createElement('form'); | |
form.setAttribute('method', method); | |
form.setAttribute('action', endpoint); | |
Object.keys(body).forEach((name) => { | |
const hiddenField = document.createElement('input'); | |
hiddenField.setAttribute('type', 'hidden'); | |
hiddenField.setAttribute('name', name); | |
hiddenField.setAttribute('value', body[name]); | |
form.appendChild(hiddenField); | |
}); | |
document.body.appendChild(form); | |
form.submit(); | |
return; | |
}; | |
formSubmit('/download/file'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment