Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React sending array of objects as form Data

I have currently created a nodejs api where a user can send data about their career. They can send text and an uploaded image.

The data is sent as follows and I have been successful with sending via postman

{
    "employee": "user",
    "positionHeld": [{
        "yearPostitionHeld": "1995 - 2000",
        "positionHeldTitle": "Manager"
    },
    {
        "yearPostitionHeld": "2000 - Present",
        "positionHeldTitle": "Assocaite Manager"
    }],
    "address": "Company Address",
    "responsibilities": ["Responsibility 1", "Responsibility 2", "Responsibility 3"]
}

I have created a front end page with ReactJS so the user can send the data as above by filling in input fields.

I set the user input via the useState Hook

const [formData, setFormData] = useState({
    companyName: "",
    year: "",
    positionHeld: [
      {
        positionHeldYear: "",
        positionHeldTitle: "",
      },
    ],
    address: "",
    responsibilities: "",
  });

via an onChange function

const onChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

I also hanle the file upload

const [fileData, setFileData] = useState();

const handleFilechange = (e) => {
    setFileData(e.target.files[0]);
  };

I first tried to send the data as the formData but the file/image always appeared in req.body and not req.file and therefore I was unable to obtain the file path.

As a solution to the file issue I then create a new formData const completeFormData = new FormData(); and appending this

const year = formData.positionHeldYear;
    const title = formData.positionHeldTitle;
    setFormData({...formData, positionHeld: {positionHeldYear: year, positionHeldTitle: title}})

completeFormData.append("companyName", formData.companyName);
    completeFormData.append("year", formData.year);
    completeFormData.append("positionHeld", formData.positionHeld); // this needs to send the array of objects
    completeFormData.append("address", formData.address);
    completeFormData.append("responsibilities", formData.responsibilities);
    completeFormData.append("image", fileData);

I am unsure if it is possible to send an array of objects as the new FormData such as the

"positionHeld": [{
        "yearPostitionHeld": "1995 - 2000",
        "positionHeldTitle": "Manager"
    },
    {
        "yearPostitionHeld": "2000 - Present",
        "positionHeldTitle": "Assocaite Manager"
    }],

When creating the new form data as above when the req.body comes to the backend the positionHeld displays as positionHeld: [object, Object] when doing a console log

How is it best to manage sending data with nest array of object strings and image uploads?

I might have gone down the wrong route with this, so hoping someone can point me in the right direction to send body and a file to confirm as my object

{
    "employee": "user",
    "positionHeld": [{
        "yearPostitionHeld": "1995 - 2000",
        "positionHeldTitle": "Manager"
    },
    {
        "yearPostitionHeld": "2000 - Present",
        "positionHeldTitle": "Assocaite Manager"
    }],
    "address": "Company Address",
    "responsibilities": ["Responsibility 1", "Responsibility 2", "Responsibility 3"]
}
like image 925
Bernard Bonjo Thompson Avatar asked Sep 16 '25 02:09

Bernard Bonjo Thompson


2 Answers

One way of sending an array in FormData is to serialize it:

completeFormData.append("positionHeld", JSON.stringify(formData.positionHeld));

Then, on the backend, you can parse it with JSON.parse().

like image 53
szilardtumo Avatar answered Sep 18 '25 17:09

szilardtumo


We did it with ReactJS(front) and ASP.Net core(back) So the best way to do it is using FormData, We use an object like below that contains an array of objects, each object includes an array of images too,

{
    CommodityID:xxxxx,
    TotalWeight:xxxx,
    CostOfCommodity:xxxx,
    Prerequisites:[{
        ProductId: xxxx,
        DeliveryWeight: xxxxx,
        ReleasedImagesUrl: [
            multiple images file
        ]
    },{
        ProductId: xxxx,
        DeliveryWeight: xxxxx,
        ReleasedImagesUrl: [
            multiple images file
        ]
    }]
}

Actually, we send each item of the array separately like Prerequisites[0].DeliveryWeight and this is the point (pairs of name/value). please pay attention to the letters that in our case first characters of items were capital (this is important too)

const formData = new FormData();
    formData.append("CommodityID", this.state.commodityId);
    formData.append("TotalWeight", this.state.totalWeight);
    formData.append("CostOfCommodity",this.state.costOfCommodity);
    for (let i = 0; i < this.state.prerequisitesListTemp.length; i++) {
      formData.append(
        `Prerequisites[${i}].ProductId`,
        this.state.prerequisitesListTemp[i].productId
      );
      formData.append(
        `Prerequisites[${i}].DeliveryWeight`,
        this.state.prerequisitesListTemp[i].deliveryWeight
      );

      for (
        let j = 0;j < this.state.prerequisitesListTemp[i].releasedImagesUrl.length;j++
      ) {
        formData.append(
          `Prerequisites[${i}].ReleasedImagesUrl`,
          this.state.prerequisitesListTemp[i].releasedImagesUrl[j]
        );
      }
    }
like image 24
Akbar Mirzaei Avatar answered Sep 18 '25 17:09

Akbar Mirzaei