bigskysoftware / bigskysoftware/htmx
Problem with Arrays in FormData Proxy
- Dominant language
- JavaScript
- Stars
- 49.4k
- Forks
- 1.7k
- Avg merge
- 3d 22h
- Merged PRs (30d)
- 30
Description
This is an issue which is related to #2616.
When trying to add an array of objects, the objects will be represented as `[object Object]`.
What do I want to do?
I want to select one or multiple files.
Then, using `htmx:configRequest`, I want to map the files to their metadata which is sent to my endpoint.
Behavior in HTMX 1.x:
```html
function convertFilesToMetadata(event) {
var files = event.detail.parameters.files;
event.detail.parameters.files = files.map((file) => ({
name: file.name,
size: file.size,
lastModified: file.lastModified,
type: file.type,
}));
}
```
Bug in HTMX 2.x:
```
function convertFilesToMetadata(event) {
var files = event.detail.parameters.files;
if (files.length < 1) {
// cancel event, no files selected
event.preventDefault();
return;
}
// convert files to dictionary of metadata
event.detail.parameters.files = files.map((file) => ({
name: file.name,
size: file.size,
lastModified: file.lastModified,
type: file.type,
}));
}
```
This will return `undefined`, since the `Proxy` does not implement `map`.
Changing map to a simple `for`, will result in the issue of `[object Object]`:
```html
function convertFilesToMetadata(event) {
console.log(event);
var files = event.detail.parameters.files;
if (files.length < 1) {
// cancel event, no files selected
event.preventDefault();
return;
}
var metadata = new Array(files.length);
for (let index = 0; index < files.length; index++) {
let file = files[index];
metadata[index] = {
name: file.name,
size: file.size,
lastModified: file.lastModified,
type: file.type,
}
}
event.detail.parameters.files = metadata;
}
```
Applying, `JSON.stringify` on the object or metadata does not help because then it will be parsed as a string of JSON and not the object itself.
Trying to assigning it directly `event.detail.parameters.files[index]` also does not work.
Other issues/breaking changes:
- A single file is now the file itself and not an array as before in 1.x
- Assigning an array with 1 element to the formData will also unpack the array
- In the other issue #2616, there is also a mention that the `FormData` object can be accesses via `event.detail.formData`, however, upon inspection it will be empty.
Contributor guide
Assessment
This issue has not been assessed yet.