#handle array ofobject has file on formData

1 messages · Page 1 of 1 (latest)

forest iris
#

i have this code i want to change array on return data as array has object { titleGallery: string, imageGallery: File }
`async function onSubmit(values: createTourFormValues) {
const formData = new FormData();

Object.entries(values).forEach(([key, value]) => {
  if (Array.isArray(value)) {
    const mappedArray = value.map((val) => {
      const obj: any = {};
      Object.entries(val).forEach(([subKey, subValue]) => {
        obj[subKey] = subValue;
      });
      return obj;
    });

    formData.append(key, JSON.stringify(mappedArray));
  } else if (value instanceof Date) {
    formData.append(key, value.toString());
  } else {
    formData.append(key, value);
  }
});

try {
  await createTour(formData);
  toast({
    className: "bg-green text-white font-semiBold",
    description: "Tour created successfully",
  });
} catch (error) {
  toast({
    className: "bg-red text-white font-semiBold",
    description: "Something went wrong, please try again.",
  });
}

}
`

silent novaBOT
#

Hi @forest iris. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the provided extracts, it seems you are trying to handle an array of objects where each object contains a title and a file. You are currently converting the array into a JSON string before appending it to the FormData object. However, FormData is designed to handle file uploads, and converting the file into a JSON string might not be the best approach.

Unfortunately, the provided extracts do not contain a direct solution to your problem. However, you can try a different approach where you append each file from the array to the FormData object individually. Here's a general idea of how you can do it:

Object.entries(values).forEach(([key, value]) => {
  if (Array.isArray(value)) {
    value.forEach((val, index) => {
      if (val.imageGallery instanceof File) {
        formData.append(`${key}[${index}][imageGallery]`, val.imageGallery, val.imageGallery.name);
      }
      if (typeof val.titleGallery === 'string') {
        formData.append(`${key}[${index}][titleGallery]`, val.titleGallery);
      }
    });
  } else if (value instanceof Date) {
    formData.append(key, value.toString());
  } else {
    formData.append(key, value);
  }
});

This code will append each file and title from the array to the FormData object with a unique key, allowing you to handle multiple files.

Please note that this is a general approach and might need adjustments based on your specific use case and server-side implementation. For more information on handling file uploads with Next.js, you can refer to the Next.js documentation (https://nextjs.org/docs/api-routes/introduction).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: