Skip to content

Commit

Permalink
fixed form content type body
Browse files Browse the repository at this point in the history
  • Loading branch information
zshao-aa committed Mar 10, 2024
1 parent cd183bb commit 15e3403
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 24 deletions.
4 changes: 1 addition & 3 deletions src/__tests__/form.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,8 @@ describe('Form', () => {
<Form
encType={'application/json'}
action={'/success'}
onSubmit={({ data, formData, formDataJson }) => {
onSubmit={({ data }) => {
data;
formData;
formDataJson;
onSubmit();
}}
control={control}
Expand Down
28 changes: 9 additions & 19 deletions src/form.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';

import getRequestBody from './logic/getRequestBody';
import get from './utils/get';
import { FieldValues, FormProps } from './types';
import { useFormContext } from './useFormContext';
Expand Down Expand Up @@ -54,41 +55,30 @@ function Form<
let type = '';

await control.handleSubmit(async (data) => {
const formData = new FormData();
let formDataJson = '';

try {
formDataJson = JSON.stringify(data);
} catch {}

for (const name of control._names.mount) {
formData.append(name, get(data, name));
}

if (onSubmit) {
await onSubmit({
data,
event,
method,
formData,
formDataJson,
});
}

if (action) {
try {
const shouldStringifySubmissionData = [
headers && headers['Content-Type'],
encType,
].some((value) => value && value.includes('json'));
const mountData: FieldValues = {};
for (const name of control._names.mount) {
mountData[name] = get(data, name);
}

const contentType = (headers && headers['Content-Type']) || encType;

const response = await fetch(action, {
method,
headers: {
...headers,
...(encType ? { 'Content-Type': encType } : {}),
...(contentType ? { 'Content-Type': contentType } : {}),
},
body: shouldStringifySubmissionData ? formDataJson : formData,
body: getRequestBody(contentType, mountData),
});

if (
Expand Down
2 changes: 0 additions & 2 deletions src/types/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,6 @@ export type SubmitHandler<TFieldValues extends FieldValues> = (
export type FormSubmitHandler<TFieldValues extends FieldValues> = (payload: {
data: TFieldValues;
event?: React.BaseSyntheticEvent;
formData: FormData;
formDataJson: string;
method?: 'post' | 'put' | 'delete';
}) => unknown | Promise<unknown>;

Expand Down

0 comments on commit 15e3403

Please sign in to comment.