Skip to content

Instantly share code, notes, and snippets.

@luc0
Last active November 4, 2020 14:44
Show Gist options
  • Save luc0/f52596416ef2c57bbc61f39007b59d98 to your computer and use it in GitHub Desktop.
Save luc0/f52596416ef2c57bbc61f39007b59d98 to your computer and use it in GitHub Desktop.
Transform JS State Object (react) to PHP object, to avoid json_encode / json_decode

Usage (manual):

formDataTransformer(formData, this.state.marketplaces, 'marketplaces');

Usage (all):

axios.post('#', createFormData(submitData), { headers: { 'Content-Type': 'multipart/form-data;' } }).then(...)

Accept Files, Dates, Objects and arrays. Iterates over infinite levels.

formatDataHelper.js

export const formDataTransformer = (formData, value, dataKey) => {
  if (value instanceof File) {
    formData.append(`${dataKey}`, value);
    return;
  }
  if (value instanceof Date || (value instanceof Object && value.constructor.name === 'Moment')) {
    formData.append(`${dataKey}`, value.toISOString());
    return;
  }

  if (value instanceof Object) {
    Object.keys(value).forEach((key) => {
      formDataTransformer(formData, value[key], `${dataKey}[${key}]`)
    })
  } else if (value instanceof Array) {
    value.forEach((currentValue, index) => {
      formDataTransformer(formData, currentValue, `${dataKey}[${index}]`)
    })
  } else {
    formData.append(`${dataKey}`, typeof value === 'undefined' || value === null || value === 'null' ? '' : value);
  }
}

export const createFormData = (data) => {
  const formData = new FormData();

  for (const element of Object.keys(data)) {
    formDataTransformer(formData, data[element], element)
  }

  return formData;
}

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