code-forge-io / code-forge-io/remix-hook-form

Arrays of files or `FileList` objects with only one element in them are not parsed as arrays

Open
#178 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
453
Forks
43
PR merge metrics
No merged PRs in 30d

Description

### Description

When an array containing only one `File` or a `FileList` of only one file is submitted, the resulting `FormData` from `generateFormData` is not an array. This is because there is only one `FormData` entry for the file.

### Suggested solution

I would suggest:
1. leveraging the existing logic in `parseFormData` that checks for `[]` suffix in keys and transforms the value to an array to handle file lists with only one element in them.
2. or Flattening the data that's being transformed to formData using something like [flattenObject](https://es-toolkit.dev/reference/object/flattenObject.html) as a more general approach to support objects of any shape/depth

### Patch

I used the following patch of `remix-hook-form@7.1.1` to fix the issue:

```patch
diff --git a/dist/chunk-RDVJQORD.js b/dist/chunk-RDVJQORD.js
index ee1875f1597cca58deaf228f4ed660857f3af092..597d94bc90bfe7a20d8fe2af29ea1f7ce88d87e9 100644
--- a/dist/chunk-RDVJQORD.js
+++ b/dist/chunk-RDVJQORD.js
@@ -92,12 +92,20 @@ var createFormData = (data, stringifyAll = true) => {
continue;
}
if (typeof FileList !== "undefined" && value instanceof FileList) {
+ if (value.length === 1) {
+ formData.append(`${key}[]`, value[0]);
+ continue;
+ }
for (let i = 0; i < value.length; i++) {
formData.append(key, value[i]);
}
continue;
}
if (Array.isArray(value) && value.length > 0 && value.every((item) => item instanceof File || item instanceof Blob)) {
+ if (value.length === 1) {
+ formData.append(`${key}[]`, value[0]);
+ continue;
+ }
for (let i = 0; i < value.length; i++) {
formData.append(key, value[i]);
}
diff --git a/dist/index.cjs b/dist/index.cjs
index c8964f29d77f11b8a162bb785c97a1e062978734..1ba4672452c7b9a53cc1224da73ed7f178847a72 100644
--- a/dist/index.cjs
+++ b/dist/index.cjs
@@ -136,12 +136,20 @@ var createFormData = (data, stringifyAll = true) => {
continue;
}
if (typeof FileList !== "undefined" && value instanceof FileList) {
+ if (value.length === 1) {
+ formData.append(`${key}[]`, value[0]);
+ continue;
+ }
for (let i = 0; i < value.length; i++) {
formData.append(key, value[i]);
}
continue;
}
if (Array.isArray(value) && value.length > 0 && value.every((item) => item instanceof File || item instanceof Blob)) {
+ if (value.length === 1) {
+ formData.append(`${key}[]`, value[0]);
+ continue;
+ }
for (let i = 0; i < value.length; i++) {
formData.append(key, value[i]);
}

```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.