useForm
useForm
is a hook that allows you to manage forms. It has some action
methods that create
, edit
and clone
the form. The hook return value comes according to the called action, and it can run different logic depending on the action
.
You can think of useForm
as a bridge between your state
and dataProvider
. It's a low-level hook that you can use to build your own form components. It's also using notificationProvider
to inform users according to the action
and dataProvider
responses.
Let's review how useForm
works behind the scenes.
- create
- edit
- clone
After form is submitted:
useForm
callsonFinish
function with the form values.onFinish
function callsuseCreate
with the form values.useCreate
callsdataProvider
'screate
function and returns the response.useForm
callsonSuccess
oronError
function with the response, depending on the response status.onSuccess
oronError
function then calls theopen
function of thenotificationProvider
to inform the user.useForm
redirects to thelist
page.
On mount, useForm
calls useGetOne
hook to retrieve the record to be edited. The id
for the record is obtained from the URL
or props
.
After form is submitted:
useForm
callsonFinish
function with the form values.onFinish
function callsuseUpdate
with the form values.useUpdate
callsdataProvider
'supdate
function and returns the response.useForm
callsonSuccess
oronError
function with the response, depending on the response status.onSuccess
oronError
function then calls theopen
function of thenotificationProvider
to inform the user.useForm
redirects to thelist
page.
On mount, useForm
calls useGetOne
hook to retrieve the record to be edited. The id
for the record is obtained from the URL
or props
.
After form is submitted:
useForm
callsonFinish
function with the form values.onFinish
function callsuseCreate
with the form values.useUpdate
callsdataProvider
'supdate
function and returns the response.useForm
callsonSuccess
oronError
function with the response, depending on the response status.onSuccess
oronError
function then calls theopen
function of thenotificationProvider
to inform the user.useForm
redirects to thelist
page.
This is the default behavior of useForm
. You can customize it by passing your own redirect
, onFinish
, onMutationSuccess
and onMutationError
props.
useForm
does not manage any state. If you're looking for a complete form library, refine
supports three form libraries out-of-the-box.
- React Hook Form (for Headless users) - Documentation - Example
- Ant Design Form (for Ant Design users) - Documentation - Example
- Mantine Form (for Mantine users) - Documentation - Example
All the data related hooks(useTable, useForm, useList etc.) of refine can be given some common properties like resource
, meta
etc.
For more information, refer to the General Concepts documentation→.
Basic Usage
We'll show the basic usage of useForm
by adding an creating form.
import { useForm } from "@refinedev/core";
import { useState } from "react";
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 theonFinish
callback. - Accepts generic type parameters. It is used to define response type of the mutation and query.
Properties
action
useForm
can handle edit
, create
and clone
actions. By default the action
is inferred from the active route. It can be overridden by passing the action
explicitly.
- create
- edit
- clone
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.
In the following example, we will show how to use useForm
with action: "create"
.
action: "edit"
is used for editing an existing record. It requires the id
to determine 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
with useOne
and returns the queryResult
for you to fill the form. After the form is submitted, it updates the record with useUpdate
.
In the following example, we'll show how to use useForm
with action: "edit"
.
action: "clone"
is used for cloning an existing record. It requires the id
to determine the record to clone. By default, it uses the id
from the route. It can be changed with the setId
function.
You can think action:clone
like save as. It's similar to action:edit
but it creates a new record instead of updating the existing one.
It fetches the record data according to the id
with useOne
and returns the queryResult
for you to fill the form. After the form is submitted, it creates a new record with useCreate
.
In the following example, we'll show how to use useForm
with action: "clone"
.
resource
Default: It reads the
resource
value from the current URL.
It will be passed to the dataProvider
's method as a params. This parameter is usually used to as a API endpoint path. It all depends on how to handle the resource
in your dataProvider
. See the creating a data provider
section for an example of how resource
are handled.
- When
action
is"create"
, it will be passed to thecreate
method from thedataProvider
. - When
action
is"edit"
, it will be passed to theupdate
and thegetOne
method from thedataProvider
. - When
action
is"clone"
, it will be passed to thecreate
and thegetOne
method from thedataProvider
.
useForm({
resource: "categories",
});
If the resource
is passed, the id
from the current URL will be ignored because it may belong to a different resource. To retrieve the id
value from the current URL, use the useParsed
hook and pass the id
value to the useForm
hook.
import { useForm, useParsed } from "@refinedev/core";
const { id } = useParsed();
useForm({
resource: "custom-resource",
id,
});
Or you can use the setId
function to set the id
value.
import { useForm } from "@refinedev/core";
const { setId } = useForm({
resource: "custom-resource",
});
setId("123");
If you have multiple resources with the same name, you can pass the identifier
instead of the name
of the resource. It will only be used as the main matching key for the resource, data provider methods will still work with the name
of the resource defined in the <Refine/>
component.
For more information, refer to the
identifier
of the<Refine/>
component documentation →
id
id
is used for determining the record to edit
or clone
. By default, it uses the id
from the route. It can be changed with the setId
function or id
property.
It is useful when you want to edit
or clone
a resource
from a different page.
id
is required when action: "edit"
or action: "clone"
.
useForm({
action: "edit", // or clone
resource: "categories",
id: 1, // <BASE_URL_FROM_DATA_PROVIDER>/categories/1
});
redirect
redirect
is used for determining the page to redirect to after the form is submitted. By default, it uses the list
. It can be changed with the redirect
property.
It can be set to "show" | "edit" | "list" | "create"
or false
to prevent the page from redirecting to the list page after the form is submitted.
useForm({
redirect: false,
});
onMutationSuccess
It's a callback function that will be called after the mutation is successful.
It receives the following parameters:
data
: Returned value fromuseCreate
oruseUpdate
depending on theaction
.variables
: The variables passed to the mutation.context
: react-query context.isAutoSave
: It's a boolean value that indicates whether the mutation is triggered by theautoSave
feature or not.
useForm({
onMutationSuccess: (data, variables, context, isAutoSave) => {
console.log({ data, variables, context, isAutoSave });
},
});
onMutationError
It's a callback function that will be called after the mutation is failed.
It receives the following parameters:
data
: Returned value fromuseCreate
oruseUpdate
depending on theaction
.variables
: The variables passed to the mutation.context
: react-query context.isAutoSave
: It's a boolean value that indicates whether the mutation is triggered by theautoSave
feature or not.
useForm({
onMutationError: (data, variables, context, isAutoSave) => {
console.log({ data, variables, context, isAutoSave });
},
});
invalidates
You can use it to manage the invalidations that will occur at the end of the mutation.
By default it's invalidates following queries from the current resource
:
- on
"create"
or"clone"
mode:"list"
and"many"
- on
"edit"
mode:"list"
","many"
and"detail"
useForm({
invalidates: ["list", "many", "detail"],
});
dataProviderName
If there is more than one dataProvider
, you should use the dataProviderName
that you will use.
It is useful when you want to use a different dataProvider
for a specific resource.
If you want to use a different dataProvider
on all resource pages, you can use the dataProvider
prop of the <Refine>
component.
useForm({
dataProviderName: "second-data-provider",
});
mutationMode
Mutation mode determines which mode the mutation runs with. Mutations can run under three different modes: pessimistic
, optimistic
and undoable
. Default mode is pessimistic
.
Each mode corresponds to a different type of user experience.
For more information about mutation modes, refer to the Mutation Mode documentation
useForm({
mutationMode: "undoable", // "pessimistic" | "optimistic" | "undoable",
});
successNotification
NotificationProvider
is required for this prop to work.
After form is submitted successfully, useForm
will call open
function from NotificationProvider
to show a success notification. With this prop, you can customize the success notification.
useForm({
successNotification: (data, values, resource) => {
return {
message: `Post Successfully created with ${data.title}`,
description: "Success with no errors",
type: "success",
};
},
});
errorNotification
NotificationProvider
is required for this prop to work.
After form is submit is failed, useForm
will call open
function from NotificationProvider
to show a success notification. With this prop, you can customize the success notification.
useForm({
errorNotification: (data, values, resource) => {
return {
message: `Something went wrong when deleting ${data.id}`,
description: "Error",
type: "error",
};
},
});
{
"message": "Error when updating <resource-name> (status code: ${err.statusCode})" or "Error when creating <resource-name> (status code: ${err.statusCode})",
"description": "Error",
"type": "error",
}
meta
meta
is a special property that can be used to pass additional information to data provider methods for the following purposes:
- Customizing the data provider methods for specific use cases.
- Generating GraphQL queries using plain JavaScript Objects (JSON).
- Filling the path parameters when generating the redirection path.
- Providing additional parameters to the redirection path after the form is submitted.
In the following example, we pass the headers
property in the meta
object to the create
method. With similar logic, you can pass any properties to specifically handle the data provider methods.
useForm({
meta: {
headers: { "x-meta-data": "true" },
},
});
const myDataProvider = {
//...
create: async ({ resource, variables, meta }) => {
const headers = meta?.headers ?? {};
const url = `${apiUrl}/${resource}`;
const { data } = await httpClient.post(url, variables, { headers });
return {
data,
};
},
//...
};
For more information, refer to the
meta
section of the General Concepts documentation →
queryMeta
In addition to the meta
property, you can also pass the queryMeta
property to the useForm
hook. This property is used to pass additional information to the useOne
hook that is used to fetch the data in the edit
and clone
modes. This is useful when you have to apply different values to the useOne
hook from the useCreate
or useUpdate
hook mutations.
useForm({
queryMeta: {
querySpecificValue: "someValue",
},
});
If you have overlapping properties in both meta
and queryMeta
, the queryMeta
property will be used.
mutationMeta
In addition to the meta
property, you can also pass the mutationMeta
property to the useForm
hook. This property is used to pass additional information to the useCreate
or useUpdate
hook mutations. This is useful when you have to apply different values to the useCreate
or useUpdate
hooks from the useOne
hook query.
useForm({
mutationMeta: {
mutationSpecificValue: "someValue",
},
});
If you have overlapping properties in both meta
and mutationMeta
, the mutationMeta
property will be used.
queryOptions
Works only in action: "edit"
or action: "clone"
mode.
in edit
or clone
mode, refine uses useOne
hook to fetch data. You can pass queryOptions
options by passing queryOptions
property.
useForm({
queryOptions: {
retry: 3,
},
});
createMutationOptions
This option is only available when action: "create"
or action: "clone"
.
In create
or clone
mode, refine uses useCreate
hook to create data. You can pass mutationOptions
by passing createMutationOptions
property.
useForm({
createMutationOptions: {
retry: 3,
},
});
updateMutationOptions
This option is only available when action: "edit"
.
In edit
mode, refine uses useUpdate
hook to update data. You can pass mutationOptions
by passing updateMutationOptions
property.
useForm({
updateMutationOptions: {
retry: 3,
},
});
liveMode
Whether to update data automatically ("auto") or not ("manual") if a related live event is received. It can be used to update and show data in Realtime throughout your app.
useForm({
liveMode: "auto",
});
For more information, refer to the Live / Realtime page
onLiveEvent
The callback function that is executed when new events from a subscription are arrived.
useForm({
onLiveEvent: (event) => {
console.log(event);
},
});
liveParams
Params to pass to liveProvider's subscribe method.
overtimeOptions
If you want loading overtime for the request, you can pass the overtimeOptions
prop to the this hook. It is useful when you want to show a loading indicator when the request takes too long.
interval
is the time interval in milliseconds. onInterval
is the function that will be called on each interval.
Return overtime
object from this hook. elapsedTime
is the elapsed time in milliseconds. It becomes undefined
when the request is completed.
const { overtime } = useForm({
//...
overtimeOptions: {
interval: 1000,
onInterval(elapsedInterval) {
console.log(elapsedInterval);
},
},
});
console.log(overtime.elapsedTime); // undefined, 1000, 2000, 3000 4000, ...
// You can use it like this:
{
elapsedTime >= 4000 && <div>this takes a bit longer than expected</div>;
}
autoSave
If you want to save the form automatically after some delay when user edits the form, you can pass true to autoSave.enabled
prop.
By default the autoSave
feature does not invalidate queries. However, you can use the invalidateOnUnmount
prop to invalidate queries upon unmount.
It also supports onMutationSuccess
and onMutationError
callback functions. You can use isAutoSave
parameter to determine whether the mutation is triggered by autoSave
or not.
autoSave
feature operates exclusively in edit
mode. Users can take advantage of this feature while editing data, as changes are automatically saved in editing mode. However, when creating new data, manual saving is still required.
onMutationSuccess
and onMutationError
callbacks will be called after the mutation is successful or failed.
enabled
Default:
false
To enable the autoSave
feature, set the enabled
parameter to true
.
useForm({
autoSave: {
enabled: true,
},
});
debounce
Default:
1000
Set the debounce time for the autoSave
prop.
useForm({
autoSave: {
enabled: true,
debounce: 2000,
},
});
invalidateOnUnmount
Default:
false
This prop is useful when you want to invalidate the list
, many
and detail
queries from the current resource when the hook is unmounted. By default, it invalidates the list
, many
and detail
queries associated with the current resource. Also, You can use the invalidates
prop to select which queries to invalidate.
useForm({
autoSave: {
enabled: true,
invalidateOnUnmount: true,
},
});
optimisticUpdateMap
If the mutation mode is defined as optimistic
or undoable
the useForm
hook will automatically update the cache without waiting for the response from the server. You may want to disable or customize this behavior. You can do this by passing the optimisticUpdateMap
prop.
This feature is only work with the mutationMode
is set to optimistic
and undoable
list
, many
and detail
are the keys of the optimisticUpdateMap
object. For automatically updating the cache, you should pass the true
. If you want not update the cache, you should pass the false
.
const { formProps, saveButtonProps } = useForm({
//...
mutationMode: "optimistic",
optimisticUpdateMap: {
list: true,
many: true,
detail: false,
},
});
In the above case the list
and many
queries will be updated automatically. But the detail
query will not be updated.
Also for customize the cache update, you can pass the function to the list
, many
and detail
keys. The function will be called with the previous
data, values
and id
parameters. You should return the new data from the function.
const { formProps, saveButtonProps } = useForm({
//...
mutationMode: "optimistic",
optimisticUpdateMap: {
list: (previous, values, id) => {
if (!previous) {
return null;
}
const data = previous.data.map((record) => {
if (record.id === id) {
return {
foo: "bar",
...record,
...values,
};
}
return record;
});
return {
...previous,
data,
};
},
many: (previous, values, id) => {
if (!previous) {
return null;
}
const data = previous.data.map((record) => {
if (record.id === id) {
return {
foo: "bar",
...record,
...values,
};
}
return record;
});
return {
...previous,
data,
};
},
detail: (previous, values) => {
if (!previous) {
return null;
}
return {
...previous,
data: {
foo: "bar",
...previous.data,
...values,
},
};
},
},
});
Return Values
queryResult
If the action
is set to "edit"
or "clone"
or if a resource
with an id
is provided, useForm
will call useOne
and set the returned values as the queryResult
property.
const { queryResult } = useForm();
const { data } = queryResult;
mutationResult
When in "create"
or "clone"
mode, useForm
will call useCreate
. When in "edit"
mode, it will call useUpdate
and set the resulting values as the mutationResult
property."
const { mutationResult } = useForm();
const { data } = mutationResult;
setId
useForm
determine id
from the router. If you want to change the id
dynamically, you can use setId
function.
const { id, setId } = useForm();
const handleIdChange = (id: string) => {
setId(id);
};
return (
<div>
<input value={id} onChange={(e) => handleIdChange(e.target.value)} />
</div>
);
redirect
"By default, after a successful mutation, useForm
will redirect
to the "list"
page. To redirect to a different page, you can either use the redirect
function to programmatically specify the destination, or set the redirect property in the hook's options.
In the following example we will redirect to the "show"
page after a successful mutation.
const { onFinish, redirect } = useForm();
// --
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const data = await onFinish(formValues);
redirect("show", data?.data?.id);
};
// --
onFinish
onFinish
is a function that is called when the form is submitted. It will call the appropriate mutation based on the action
property.
You can override the default behavior by passing an onFinish
function in the hook's options.
For example you can change values before sending to the API.
formLoading
Loading state of a modal. It's true
when useForm
is currently being submitted or data is being fetched for the "edit"
or "clone"
mode.
overtime
overtime
object is returned from this hook. elapsedTime
is the elapsed time in milliseconds. It becomes undefined
when the request is completed.
const { overtime } = useForm();
console.log(overtime.elapsedTime); // undefined, 1000, 2000, 3000 4000, ...
autoSaveProps
If autoSave
is enabled, this hook returns autoSaveProps
object with data
, error
, and status
properties from mutation.
FAQ
How can Invalidate other resources?
You can invalidate other resources with help of useInvalidate
hook.
It is useful when you want to invalidate
other resources don't have relation with the current resource.
import { useForm, useInvalidate } from "@refinedev/core";
const PostEdit = () => {
const invalidate = useInvalidate();
useForm({
onMutationSuccess: (data, variables, context) => {
invalidate({
resource: "users",
invalidates: ["resourceAll"],
});
},
});
// ---
};
How can I change the form data before submitting it to the API?
You may need to modify the form data before it is sent to the API.
For example, Let's send the values we received from the user in two separate inputs, name
and surname
, to the API as fullName
.
import { useForm } from "@refinedev/core";
import React, { useState } from "react";
export const UserCreate: React.FC = () => {
const [name, setName] = useState();
const [surname, setSurname] = useState();
const { onFinish } = useForm();
const onSubmit = (e) => {
e.preventDefault();
const fullName = `${name} ${surname}`;
onFinish({
fullName: fullName,
name,
surname,
});
};
return (
<form onSubmit={onSubmit}>
<input onChange={(e) => setName(e.target.value)} />
<input onChange={(e) => setSurname(e.target.value)} />
<button type="submit">Submit</button>
</form>
);
};
How to pass meta
values only for the mutation or query?
You can use meta
property to pass common values to the mutation and the query. But in some cases, you may want to pass different values to the mutation and the query. To do this, you can use mutationMeta
and queryMeta
properties.
API Reference
Properties
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
Property | Desription | Type | Default |
---|---|---|---|
TQueryFnData | Result data returned by the query function. Extends BaseRecord | BaseRecord | BaseRecord |
TError | Custom error object that extends HttpError | HttpError | HttpError |
TVariables | Values for params. | {} | |
TData | Result data returned by the select function. Extends BaseRecord . If not specified, the value of TQueryFnData will be used as the default value. | BaseRecord | TQueryFnData |
TResponse | Result data returned by the mutation function. Extends BaseRecord . If not specified, the value of TData will be used as the default value. | BaseRecord | TData |
TResponseError | Custom error object that extends HttpError . If not specified, the value of TError will be used as the default value. | HttpError | TError |
Return values
Property | Description | Type |
---|---|---|
onFinish | Triggers the mutation | (values: TVariables) => Promise<CreateResponse<TData> | UpdateResponse<TData> | void > |
queryResult | Result of the query of a record | QueryObserverResult<T> |
mutationResult | Result of the mutation triggered by calling onFinish | UseMutationResult<T> |
formLoading | Loading state of form request | boolean |
id | Record id for clone and create action | BaseKey |
setId | id setter | Dispatch<SetStateAction< string | number | undefined>> |
redirect | Redirect function for custom redirections | (redirect: "list" |"edit" |"show" |"create" | false ,idFromFunction?: BaseKey |undefined ) => data |
overtime | Overtime loading props | { elapsedTime?: number } |
autoSaveProps | Auto save props | { data: UpdateResponse<TData> | undefined, error: HttpError | null, status: "loading" | "error" | "idle" | "success" } |
Example
npm create refine-app@latest -- --example form-core-use-form
- Basic Usage
- Properties
action
resource
id
redirect
onMutationSuccess
onMutationError
invalidates
dataProviderName
mutationMode
successNotification
errorNotification
meta
queryMeta
mutationMeta
queryOptions
createMutationOptions
updateMutationOptions
liveMode
onLiveEvent
liveParams
overtimeOptions
autoSave
enabled
debounce
invalidateOnUnmount
optimisticUpdateMap
- Return Values
queryResult
mutationResult
setId
redirect
onFinish
formLoading
overtime
autoSaveProps
- FAQ
- How can Invalidate other resources?
- How can I change the form data before submitting it to the API?
- How to pass
meta
values only for the mutation or query? - API Reference
- Properties
- Type Parameters
- Return values
- Example