DEV Community 👩‍💻👨‍💻

Max Frolov
Max Frolov

Posted on

It's so annoying in 2020 you have to work with an ancient API which forces to use FormData

Here is a FormData helper for plain Object:

export const getFormData = (input) => {
  const formData = new FormData();

  Object.keys(input).forEach((key) => {
    if (typeof !input[key] === "undefined") {
      return;
    }

    Array.isArray(input[key])
      ? (input[key]).forEach((value) => formData.append(`${key}[]`, value))
      : formData.append(key, `${input[key]}`);
  });

  return formData;
};

More tips and best practices on my Twitter.

Top comments (0)

🤔 Did you know?

 
🌚 Dark mode is available in Settings.