|
- import * as React from 'react';
- import {
- ENCTYPE_APPLICATION_JSON,
- ENCTYPE_MULTIPART_FORM_DATA,
- } from '../../common';
- import {
- DEFAULT_ENCTYPE_SERIALIZERS,
- EncTypeSerializerMap,
- SerializerOptions,
- } from '../../utils/serialization';
- import {
- AllowedClientMethod,
- AllowedServerMethod,
- FormDerivedElement,
- FormDerivedElementComponent,
- } from '../common';
- import { useFormFetch } from '../hooks/useFormFetch';
-
- export interface FormProps extends Omit<React.HTMLProps<FormDerivedElement>, 'action' | 'method'> {
- action?: string;
- method?: AllowedServerMethod;
- clientAction?: string;
- clientHeaders?: HeadersInit;
- clientMethod?: AllowedClientMethod;
- invalidate?: (...args: unknown[]) => unknown;
- refresh?: (response: Response) => void;
- encTypeSerializers?: EncTypeSerializerMap;
- responseEncType?: string;
- serializerOptions?: SerializerOptions;
- disableFetch?: boolean;
- }
-
- export const Form = React.forwardRef<FormDerivedElement, FormProps>(({
- children,
- onSubmit,
- action,
- method = 'get' as const,
- clientAction = action,
- clientMethod = method,
- clientHeaders,
- encType = ENCTYPE_MULTIPART_FORM_DATA,
- invalidate,
- refresh,
- encTypeSerializers = DEFAULT_ENCTYPE_SERIALIZERS,
- responseEncType = ENCTYPE_APPLICATION_JSON,
- serializerOptions,
- disableFetch = false,
- ...etcProps
- }, forwardedRef) => {
- const { handleSubmit } = useFormFetch({
- clientAction,
- onSubmit,
- clientMethod,
- clientHeaders,
- encType,
- invalidate,
- refresh,
- encTypeSerializers,
- responseEncType,
- serializerOptions,
- });
-
- const serverMethodRaw = method.toLowerCase();
- const serverMethod = serverMethodRaw === 'get' ? 'get' : 'post';
-
- return (
- <FormDerivedElementComponent
- {...etcProps}
- ref={forwardedRef}
- onSubmit={disableFetch ? onSubmit : handleSubmit}
- action={action}
- method={serverMethod}
- encType={ENCTYPE_MULTIPART_FORM_DATA}
- >
- {children}
- </FormDerivedElementComponent>
- );
- });
-
- Form.displayName = 'Form' as const;
-
- Form.defaultProps = {
- action: undefined,
- clientAction: undefined,
- clientHeaders: undefined,
- clientMethod: undefined,
- encTypeSerializers: DEFAULT_ENCTYPE_SERIALIZERS,
- disableFetch: false as const,
- invalidate: undefined,
- method: 'get' as const,
- refresh: undefined,
- responseEncType: ENCTYPE_APPLICATION_JSON,
- serializerOptions: undefined,
- };
|