Skip to main content
Version: 3.xx.xx

useForm

useForm is a hook that allows to manage forms. It has some action methods that create, edit and clone the form. The hook return value comes to according to the called action and it can run different logic depending on the action.

info

If you're looking for a complete form library, Refine supports two form libraries out-of-the-box.

Basic Usage​

We'll show the basic usage of useForm by adding an creating form.

src/posts/create.tsx
import { useState } from "react";
import { useForm } from "@pankod/refine-core";

export const PostCreate = () => {
const [title, setTitle] = useState();
const { onFinish } = useForm({
action: "create",
});

const onSubmit = (e) => {
e.preventDefault();
onFinish({ title });
};

return (
<form onSubmit={onSubmit}>
<input onChange={(e) => setTitle(e.target.value)} />
<button type="submit">Submit</button>
</form>
);
};
  • Returns the mutationResult after called the onFinish callback.
  • Accepts generic type parameters. It is used to define response type of the mutation and query.

Actions​

useForm can handle edit, create and clone actions.

tip

By default, it determines the action from route. In the above example, the route is /posts/create thus the hook will be called with action: "create". If the route is /posts/edit/1, the hook will be called with action: "edit".

It can be overridden by passing the action prop where it isn't possible to determine the action from the route (e.g. when using form in a modal or using a custom route).

action: "edit"​

action: "edit" is used for editing an existing record. It requires the id for determining the record to edit. By default, it uses the id from the route. It can be changed with the setId function or id property.

It fetches the record data according to the id and returns the queryResult for you to fill the form.

useForm uses useUpdate under the hood for mutations on edit mode.

action: "create"​

action: "create"is used for creating a new record that didn't exist before.

useForm uses useCreate under the hood for mutations on create mode.

action: "clone"​

action: "clone" is used for cloning an existing record. It requires the id for determining the record to clone. By default, it uses the id from the route. It can be changed with the setId function.

It fetches the record data according to the id and returns the queryResult for you to fill the form.

useForm uses useUpdate under the hood for mutations on clone mode.

API Reference​

Properties​

PropertyDescriptionTypeDefault
actionType of the form mode"edit" | "create" | "clone"Action that it reads from route otherwise "create" is used
resourceResource name for API data interactionsResource name that it reads from route stringResource name that it reads from route
idRecord id for fetchingBaseKeyId that it reads from the URL
mutationModeDetermines when mutations are executed "pessimistic | "optimistic | "undoable""pessimistic"*
onMutationSuccessCalled when a mutation is successful(data: UpdateResponse<M>, variables: any, context: any) => void
onMutationErrorCalled when a mutation encounters an error(error: any, variables: any, context: any) => void
redirectPage to redirect after a succesfull mutation "show" | "edit" | "list" | "create" | false"list"
undoableTimeoutDuration to wait before executing mutations when mutationMode = "undoable"number5000*
successNotificationSuccessful Mutation notificationSuccessErrorNotification"Successfully created resource" or "Successfully updated resource"
errorNotificationUnsuccessful Mutation notificationSuccessErrorNotification"There was an error creating resource (status code: statusCode)" or "Error when updating resource (status code: statusCode)"
metaDataMetadata query for dataProviderMetaDataQuery{}
dataProviderNameIf there is more than one dataProvider, you should use the dataProviderName that you will use.string{}
liveModeWhether to update data automatically ("auto") or not ("manual") if a related live event is received. The "off" value is used to avoid creating a subscription."auto" | "manual" | "off""off"
liveParamsParams to pass to liveProvider's subscribe method if liveMode is enabled.{ ids?: BaseKey[]; [key: string]: any; }undefined
onLiveEventCallback to handle all related live events of this hook.(event: LiveEvent) => voidundefined
invalidatesYou can use it to manage the invalidations that will occur at the end of the mutation.all, resourceAll, list, many, detail, false["list", "many", "detail"]
queryOptionsreact-query queryOptions of useOne hook used while in edit mode. UseQueryOptions<
{ data: TData[]; },
TError>

*: These props have default values in RefineContext and can also be set on <Refine> component. useForm will use what is passed to <Refine> as default but a local value will override it.

Type Parameters​

PropertyDesriptionDefault
TDataResult data of the query that extends BaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpError
TVariablesValues for params.{}

Return values​

PropertyDescriptionType
onFinishTriggers the mutation(values: TVariables) => Promise<CreateResponse<TData> | UpdateResponse<TData> | void>
queryResultResult of the query of a recordQueryObserverResult<T>
mutationResultResult of the mutation triggered by calling onFinishUseMutationResult<T>
formLoadingLoading state of form requestboolean
idRecord id for clone and create actionBaseKey
setIdid setterDispatch<SetStateAction< string | number | undefined>>
redirectRedirect function for custom redirections(redirect: "list"|"edit"|"show"|"create"| false ,idFromFunction?: BaseKey|undefined) => data

useModal hook allows you to manage a modal. Since it is designed as headless, it only outputs show and close functions and visible for state. It expects you to handle the UI.

You can use the visible state to show or hide the modal.