Skip to content

Commit

Permalink
Merge pull request #150 from videvide/fix-file-uploads
Browse files Browse the repository at this point in the history
Fix: file uploads
  • Loading branch information
AlemTuzlak authored Jan 21, 2025
2 parents 7bbaef9 + 3ee612c commit 71f7ed5
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/utilities/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ describe("parseFormData", () => {
mockFormData.append("formData", blob);
requestFormDataSpy.mockResolvedValueOnce(mockFormData);
const data = await parseFormData<{ formData: any }>(request);
expect(data.formData).toBeTypeOf("string");
expect(data.formData).toBeTypeOf("object");
});
});

Expand Down
15 changes: 10 additions & 5 deletions src/utilities/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import type { FieldErrors, FieldValues, Resolver } from "react-hook-form";

const tryParseJSON = (jsonString: string) => {
const tryParseJSON = (value: string | File | Blob) => {
if (value instanceof File || value instanceof Blob) {
return value;
}
try {
const json = JSON.parse(jsonString);
const json = JSON.parse(value);

return json;
} catch (e) {
return jsonString;
return value;
}
};

Expand All @@ -25,7 +28,7 @@ export const generateFormData = (
// Iterate through each key-value pair in the form data.
for (const [key, value] of formData.entries()) {
// Try to convert data to the original type, otherwise return the original value
const data = preserveStringified ? value : tryParseJSON(value.toString());
const data = preserveStringified ? value : tryParseJSON(value);
// Split the key into an array of parts.
const keyParts = key.split(".");
// Initialize a variable to point to the current object in the output object.
Expand Down Expand Up @@ -171,16 +174,18 @@ export const createFormData = <T extends FieldValues>(
}
continue;
}
// Handle array of File and Blob objects
if (
Array.isArray(value) &&
value.length > 0 &&
(value[0] instanceof File || value[0] instanceof Blob)
value.every((item) => item instanceof File || item instanceof Blob)
) {
for (let i = 0; i < value.length; i++) {
formData.append(key, value[i]);
}
continue;
}
// Handle File or Blob
if (value instanceof File || value instanceof Blob) {
formData.append(key, value);
continue;
Expand Down

0 comments on commit 71f7ed5

Please sign in to comment.