Search code examples
javascriptreactjsform-data

How to send an array of objects inside form data in React JS?


I have been trying to send an array of objects inside a form data using React JS at the backend. When I am pushing the data inside form data using its append method, it is showing my array as this

SurveyAnswers: [object object, object, object]

in browsers network tab but we have been receiving null at the backend. We have checked the backend API it is working fine when we are sending data using postman, But, when data is being sent through frontend, it is having a problem. Following is my code snippet:

const answers = [ 
  {
    Answer: "Hello World",
    QuestionId: 26,
    UserId: 190
  },
  {
    Answer: "Document",
    File: file,
    UserId: 190,
    QuestionId: 23
  }
]

const onSubmit = () => {
  const data = new FormData();
  data.append("SurveyAnswers", answers);
  const res = await executeAddSurveyFormAnswers({ data: data });     
  console.log('response, res);
}

Solution

  • If you're trying to pass an object, you will need to "stringify" the object

    data.append("SurveyAnswers", JSON.stringify(answers))

    Then on the backend, you will need to "Parse" or "Deserialize" the string to convert back to an object. I don't know what language you are using for server side, but you can do a search for "parse json string in XXX" <-XXX is the language (ie.. C#)