Skip to content

Instantly share code, notes, and snippets.

@dan-dr
Last active September 20, 2019 01:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dan-dr/b90b94c4dac82517602caffa3155e7f3 to your computer and use it in GitHub Desktop.
Save dan-dr/b90b94c4dac82517602caffa3155e7f3 to your computer and use it in GitHub Desktop.
Netlify formData object from value
<form>
<input type="text" name="cities[]" /> <!-- for arrays and objects. don't enumerate/propertize in markup. yes i just invented propertize -->
</form>
import toNetlifyFormData from './whatever'
let formData = toNetlifyFormData({
cities: [{name: 'Chicago', state: 'IL', stuff: { population: 'many', religion: 'pastafarians' }}, {name: 'Los Angeles', state: 'CA'}]
})
let formData = toNetlifyFormData({
cities: ['Chicago', 'Los Angeles']
})
// both will be valid
const response = await axios({
method: 'post',
url: '/',
data: formData,
config: {
headers: { 'Content-Type': 'multipart/form-data; charset="utf-8"' },
},
})
export default function toNetlifyFormData(value, formData = new FormData(), key = '') {
if (value instanceof Array) {
value.forEach((element, index) => {
const tempFormKey = `${key}[]`
toNetlifyFormData(element, formData, tempFormKey)
})
} else if (value instanceof Date) {
formData.append(key, value.toISOString())
} else if (
typeof value === 'object' &&
value !== null &&
!(value instanceof File)
) {
Object.keys(value).forEach(k =>
toNetlifyFormData(value[k], formData, key ? `${key}[${k}]` : k)
)
} else {
formData.append(
key,
typeof value === 'undefined' || value === null ? '' : value
)
}
return formData
}
@anaibol
Copy link

anaibol commented Sep 19, 2019

Great job! Does it work?

@dan-dr
Copy link
Author

dan-dr commented Sep 20, 2019

Works for me :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment