Skip to main content
Version: 4.xx.xxSource Code

useForm

http://localhost:3000
import React from "react";
import {
Refine,
LayoutProps,
useList,
HttpError,
useShow,
useNavigation,
} from "@refinedev/core";

import { Layout } from "components";

import { PostList, PostCreate, PostEdit, PostShow } from "pages/posts";

import routerProvider from "@refinedev/react-router-v6";

import { BrowserRouter, Routes, Route, Outlet, Link } from "react-router-dom";

type FormValues = Omit<IPost, "id">;

interface IPost {
id: number;
title: string;
content: string;
}

const Layout: React.FC<LayoutProps> = ({ children }) => {
return (
<div
style={{
background: "white",
height: "100vh",
}}
>
{children}
</div>
);
};

const PAGE_SIZE = 10;

const PostList: React.FC = () => {
const [page, setPage] = React.useState(1);

const { edit, create, clone } = useNavigation();

const { data } = useList<IPost>({
resource: "posts",
pagination: {
current: page,
pageSize: PAGE_SIZE,
},
});

const posts = data?.data || [];
const toalCount = data?.total || 0;

const pageCount = Math.ceil(toalCount / PAGE_SIZE);
const hasNext = page * PAGE_SIZE < toalCount;
const hasPrev = page > 1;

return (
<div>
<div>
<button onClick={() => create("posts")}>
<span>Create Post</span>
</button>
</div>

<table>
<thead>
<tr>
<th>
<div>ID</div>
</th>
<th>
<div>Title</div>
</th>

<th>
<div>Action</div>
</th>
</tr>
</thead>
<tbody>
{posts.map((post) => (
<tr key={post.id}>
<td>{post.id}</td>
<td>{post.title}</td>
<td>
<div>
<button
onClick={() => edit("posts", post.id)}
>
Edit
</button>
<button
onClick={() => edit("posts", post.id)}
>
Clone
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
<div>
<div>
<button onClick={() => setPage(1)} disabled={!hasPrev}>
First
</button>
<button
onClick={() => setPage((prev) => prev - 1)}
disabled={!hasPrev}
>
Previous
</button>
<button
onClick={() => setPage((prev) => prev + 1)}
disabled={!hasNext}
>
Next
</button>
<button
onClick={() => setPage(pageCount)}
disabled={!hasNext}
>
Last
</button>
</div>
<span>
Page{" "}
<strong>
{page} of {pageCount}
</strong>
</span>
<span>
Go to page:
<input
type="number"
defaultValue={page + 1}
onChange={(e) => {
const value = e.target.value
? Number(e.target.value)
: 1;
setPage(value);
}}
/>
</span>
</div>
</div>
);
};

const PostEdit: React.FC = () => {
const { formLoading, onFinish, queryResult } = useForm<FormValues>();
const defaultValues = queryResult?.data?.data;

const [formValues, seFormValues] = useState<FormValues>({
title: defaultValues?.title || "",
content: defaultValues?.content || "",
});

const handleOnChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
) => {
seFormValues({
...formValues,
[e.target.name]: e.target.value,
});
};

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
onFinish(formValues);
};

useEffect(() => {
seFormValues({
title: defaultValues?.title || "",
content: defaultValues?.content || "",
});
}, [defaultValues]);

return (
<div>
<br />
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="title">Title</label>
<input
type="text"
id="title"
name="title"
placeholder="Title"
value={formValues.title}
onChange={handleOnChange}
/>
</div>
<div>
<label htmlFor="content">Content</label>
<textarea
id="content"
name="content"
placeholder="Content"
rows={10}
value={formValues.content}
onChange={handleOnChange}
/>
</div>
<button type="submit" disabled={formLoading}>
{formLoading && <div>Loading...</div>}
<span>Save</span>
</button>
</form>
</div>
);
};

const PostCreate: React.FC = () => {
const { formLoading, onFinish } = useForm<IPost, HttpError, FormValues>();

const [formValues, seFormValues] = useState<FormValues>({
title: "",
content: "",
});

const handleOnChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
) => {
seFormValues({
...formValues,
[e.target.name]: e.target.value,
});
};

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
onFinish(formValues);
};

return (
<div>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="title">Title</label>
<input
type="text"
id="title"
name="title"
placeholder="Title"
value={formValues.title}
onChange={handleOnChange}
/>
</div>

<div>
<label htmlFor="content">Content</label>
<textarea
id="content"
name="content"
placeholder="Content"
value={formValues.content}
onChange={handleOnChange}
/>
</div>
<button type="submit" disabled={formLoading}>
{formLoading && <div>Loading...</div>}
<span>Save</span>
</button>
</form>
</div>
);
};

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.

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 use notificationProvider to inform users according to the action and dataProvider response.

Let's review how useForm works behind the scenes.

After form is submitted:

  1. useForm calls onFinish function with the form values.
  2. onFinish function calls useCreate with the form values.
  3. useCreate calls dataProvider's create function and returns the response.
  4. useForm calls onSuccess or onError function with the response, depending on the response status.
  5. onSuccess or onError function then calls the open function of the notificationProvider to inform the user.
  6. useForm, redirects to the list page.

This is the default behavior of useForm. You can customize it by passing your own redirect, onFinish, onMutationSuccess and onMutationError props.

info

useForm does not manage any state. If you're looking for a complete form library, refine supports three form libraries out-of-the-box.

tip

All the data related hooks(useTable, useForm, useList etc.) of refine can be given some common properties like resource, meta etc.

Please refer to General Concepts for more information.

Basic Usage

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

import { useState } from "react";
import { useForm } from "@refinedev/core";

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.

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.

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'll show how to use useForm with action: "create".

http://localhost:3000
import React, { useState } from "react";
import { useForm } from "@refinedev/core";

interface FormValues {
id: number;
title: string;
content: string;
}

const PostCreatePage: React.FC = () => {
const { formLoading, onFinish } = useForm<IPost, HttpError, FormValues>();

const [formValues, seFormValues] = useState<FormValues>({
title: "",
content: "",
});

const handleOnChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
) => {
seFormValues({
...formValues,
[e.target.name]: e.target.value,
});
};

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
onFinish(formValues);
};

return (
<div>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="title">Title</label>
<input
type="text"
id="title"
name="title"
placeholder="Title"
value={formValues.title}
onChange={handleOnChange}
/>
</div>

<div>
<label htmlFor="content">Content</label>
<textarea
id="content"
name="content"
placeholder="Content"
value={formValues.content}
onChange={handleOnChange}
/>
</div>
<button type="submit" disabled={formLoading}>
{formLoading && <div>Loading...</div>}
<span>Save</span>
</button>
</form>
</div>
);
};

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.

useForm({
resource: "categories",
});
caution

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");

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.

Note: 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 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 from useCreate or useUpdate depending on the action.
  • variables: The variables passed to the mutation.
  • context: react-query context.
useForm({
onMutationSuccess: (data, variables, context) => {
console.log({ data, variables, context });
},
});

onMutationError

It's a callback function that will be called after the mutation is failed.

It receives the following parameters:

  • data: Returned value from useCreate or useUpdate depending on the action.
  • variables: The variables passed to the mutation.
  • context: react-query context.
useForm({
onMutationError: (data, variables, context) => {
console.log({ data, variables, context });
},
});

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.

tip

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, please check Mutation Mode documentation page.

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",
};
},
});
Default values
{
"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 used following three purposes:

  • To pass additional information to data provider methods.
  • Generate GraphQL queries using plain JavaScript Objects (JSON). Please refer GraphQL for more information.
  • When generating the redirection path, properties in meta will also be checked to fill in the path parameters.
  • To provide additional parameters to the redirection path after the form is submitted. If your route has additional parameters, you can use meta to provide them.

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,
};
},
//...
};

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. For more information about live mode, please check Live / Realtime page.

useForm({
liveMode: "auto",
});

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.

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.

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 { useInvalidate, useForm } 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.

src/users/create.tsx
import React, { useState } from "react";
import { useForm } from "@refinedev/core";

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>
);
};

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

PropertyDesriptionTypeDefault
TDataResult data returned by the query function. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
TVariablesValues for params.{}
TSelectDataResult data returned by the select function. Extends BaseRecord. If not specified, the value of TData will be used as the default value.BaseRecordTData

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

Example

RUN IN YOUR LOCAL
npm create refine-app@latest -- --example form-core-use-form