Last active
September 20, 2019 01:09
-
-
Save dan-dr/b90b94c4dac82517602caffa3155e7f3 to your computer and use it in GitHub Desktop.
Netlify formData object from value
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
<form> | |
<input type="text" name="cities[]" /> <!-- for arrays and objects. don't enumerate/propertize in markup. yes i just invented propertize --> | |
</form> |
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
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"' }, | |
}, | |
}) |
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great job! Does it work?