Riya Yadav
Riya Yadav

Reputation: 177

How to pass array to formdata and save as array in react.js

i am passing an array to formdata but getting it as string. How can i save it in array only.

tags=["abc", "def", "ghi"]
formData.set("tags",tags);

if i do this at frontend then nothing is getting save at backend

const clickSubmit = (event) => {
    event.preventDefault();
    setValues({ ...values, error: "", loading: true });
    tags.forEach((tag) => formData.append("tags[]", tag));
    createProduct(formData).then((data) => {
      if (data.error) {
        setValues({ ...values, error: data.error });
      } else {
        setValues({
          ...values,
          name: "",
          description: "",
        });
      }
    });
  };

the backend code after submitting form

exports.create = (req, res) => {
  console.log("REQ", req.body);
  let form = new formidable.IncomingForm();
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    if (err) {
      return res.status(400).json({
        error: "Image could not be uploaded",
      });
    }
    let product = new Product(fields);
    console.log("P", product);

    if (files.photo) {
      product.photo.data = fs.readFileSync(files.photo.path);
      product.photo.contentType = files.photo.type;
    }

    product.save((err, result) => {
      if (err) {
        return res.status(400).json({
          error: errorHandler(err),
        });
      }
      res.json(result);
    });
  });
};

also the req.body giving empty object,why so i have use

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

Upvotes: 3

Views: 7631

Answers (1)

Iqbal
Iqbal

Reputation: 219

this is not how we pass an array to formData. you have to loop through all the array items and add them to formData one by one.

const frmData = new FormData();
const tags = ["abc", "def", "ghi"];
tags.forEach(tag => frmData.append('tags[]', tag))

So the takeaway here is that when you want to add an array to form data you have to use key name as "key[]" with the array symbol at the end.

Upvotes: 4

Related Questions