Limiting repetation in Formik FormData

Viewed 101

It is rare that I send FormData via Formik, but when I do, it becomes very repetitive i.e.


formData.append(k,v)
formData.append(k,v)
formData.append(k,v)

and I do this when there is only one or two file(s) to upload, I wish to remove the repetition which is present here.

I tried a couple of ways

  let formData = new FormData();
  Object.keys(values).forEach((key) => formData.append(key, values[key]));

and

  for (let key in values) {
    formData.append(key, values[key]);
  }

but those did not work with Formik. Is there any solution to it?

1 Answers

There is obj-to-formdata, which abstracts the repetition and handles nested objects:

https://github.com/therealparmesh/object-to-formdata

const data = {
    title: 'title',
    text: 'text',
    preview: {p_title:'p title', p_text: 'p text'}
};

const formData = objectToFormData(data);

It handles File objects too.

Related