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

useForm

http://localhost:3000
import React from "react";
import { useTable } from "@refinedev/react-table";
import { ColumnDef, flexRender } from "@tanstack/react-table";

import {
Edit as MantineEdit,
Create as MantineCreate,
List as MantineList,
useTable as useMantineTable,
EditButton as MantineEditButton,
CloneButton as MantineCloneButton,
} from "@refinedev/mantine";
import {
Input as MantineInput,
Box as MantineBox,
Group as MantineGroup,
ScrollArea as MantineScrollArea,
Table as MantineTable,
Pagination as MantinePagination,
TextInput as MantineTextInput,
Text as MantineText,
Textarea as MantineTextarea,
} from "@mantine/core";

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

const PostList: React.FC = () => {
const columns = React.useMemo<ColumnDef<IPost>[]>(
() => [
{
id: "id",
header: "ID",
accessorKey: "id",
},
{
id: "title",
header: "Title",
accessorKey: "title",
meta: {
filterOperator: "contains",
},
},

{
id: "actions",
header: "Actions",
accessorKey: "id",
enableColumnFilter: false,
enableSorting: false,
cell: function render({ getValue }) {
return (
<MantineGroup spacing="xs" noWrap>
<MantineEditButton
hideText
recordItemId={getValue() as number}
/>
<MantineCloneButton
hideText
recordItemId={getValue() as number}
/>
</MantineGroup>
);
},
},
],
[],
);

const {
getHeaderGroups,
getRowModel,
refineCore: { setCurrent, pageCount, current },
} = useTable({
columns,
});

return (
<MantineScrollArea>
<MantineList>
<MantineTable highlightOnHover>
<thead>
{getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<th key={header.id}>
{!header.isPlaceholder && (
<MantineGroup
spacing="xs"
noWrap
>
<MantineBox>
{flexRender(
header.column
.columnDef
.header,
header.getContext(),
)}
</MantineBox>
</MantineGroup>
)}
</th>
);
})}
</tr>
))}
</thead>
<tbody>
{getRowModel().rows.map((row) => {
return (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => {
return (
<td key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</td>
);
})}
</tr>
);
})}
</tbody>
</MantineTable>
<br />
<MantinePagination
position="right"
total={pageCount}
page={current}
onChange={setCurrent}
/>
</MantineList>
</MantineScrollArea>
);
};

const PostEdit: React.FC = () => {
const { saveButtonProps, getInputProps, errors } = useForm({
initialValues: {
title: "",
content: "",
},
validate: {
title: (value) =>
value.length < 3 && "Title must be at least 3 characters",
content: (value) =>
value.length < 10 && "Content must be at least 10 characters",
},
});

return (
<MantineEdit saveButtonProps={saveButtonProps}>
<form>
<MantineTextInput
mt={8}
label="Title"
placeholder="Title"
withAsterisk
{...getInputProps("title")}
/>

<MantineTextarea
label="Content"
placeholder="Content"
minRows={4}
maxRows={4}
withAsterisk
{...getInputProps("content")}
/>
</form>
</MantineEdit>
);
};

const PostCreate: React.FC = () => {
const { saveButtonProps, getInputProps, errors } = mantineUseForm({
initialValues: {
title: "",
content: "",
},
validate: {
title: (value) =>
value.length < 3 && "Title must be at least 3 characters",
content: (value) =>
value.length < 10 && "Content must be at least 10 characters",
},
});

return (
<MantineCreate saveButtonProps={saveButtonProps}>
<form>
<MantineTextInput
mt={8}
label="Title"
placeholder="Title"
withAsterisk
{...getInputProps("title")}
/>
<MantineTextarea
label="Content"
placeholder="Content"
minRows={4}
maxRows={4}
withAsterisk
{...getInputProps("content")}
/>
</form>
</MantineCreate>
);
};

useForm is used to manage forms. It is based on Mantine useForm and refine useForm to supports all the features of these packages and adds some additional features.

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

For more detailed usage examples please refer to the Mantine Form documentation.

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

import { Edit, useForm } from "@refinedev/mantine";
import { Select, TextInput } from "@mantine/core";

const PostEdit: React.FC = () => {
const { saveButtonProps, getInputProps } = useForm({
initialValues: {
title: "",
status: "",
},
validate: {
title: (value) => (value.length < 2 ? "Too short title" : null),
status: (value) =>
value.length <= 0 ? "Status is required" : null,
},
});

return (
<Edit saveButtonProps={saveButtonProps}>
<form>
<TextInput
mt={8}
label="Title"
placeholder="Title"
withAsterisk
{...getInputProps("title")}
/>
<Select
mt={8}
label="Status"
placeholder="Pick one"
data={[
{ label: "Published", value: "published" },
{ label: "Draft", value: "draft" },
{ label: "Rejected", value: "rejected" },
]}
withAsterisk
{...getInputProps("status")}
/>
</form>
</Edit>
);
};

In the example if you navigate to /posts/edit/1234 it will manage the data of the post with id of 1234 in an editing context. See Actions on how useForm determines this is an editing context.

Since this is an edit form it will fill the form with the data of the post with id of 1234 and then the form will be ready to edit further and submit the changes.

Submit functionality is provided by saveButtonProps which includes all of the necessary props for a button to submit a form including automatically updating loading states.

tip

If you want to show a form in a modal or drawer where necessary route params might not be there you can use the useModalForm or the useDrawerForm hook.

Properties

action

useForm can handle edit, create and clone actions.

tip

By default, it determines the action from route. The action is inferred by matching the resource's action path with the current route.

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: "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 from "react";

import { Create, useForm } from "@refinedev/mantine";
import { Text, TextInput, Textarea } from "@mantine/core";

const PostCreatePage: React.FC = () => {
const { saveButtonProps, getInputProps, errors } = useForm({
initialValues: {
title: "",
content: "",
},
validate: {
title: (value) =>
value.length < 3 && "Title must be at least 3 characters",
content: (value) =>
value.length < 10 && "Content must be at least 10 characters",
},
});

return (
<Create saveButtonProps={saveButtonProps}>
<form>
<TextInput
mt={8}
label="Title"
placeholder="Title"
withAsterisk
{...getInputProps("title")}
/>
<Textarea
label="Content"
placeholder="Content"
minRows={4}
maxRows={4}
withAsterisk
{...getInputProps("content")}
/>
</form>
</Create>
);
};

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({
refineCoreProps: {
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 } from "@refinedev/mantine";
import { useParsed } from "@refinedev/core";

const { id } = useParsed();

useForm({
refineCoreProps: {
resource: "custom-resource",
id,
},
});

Or you can use the setId function to set the id value.

import { useForm } from "@refinedev/mantine";

const {
refineCore: { setId },
} = useForm({
refineCoreProps: {
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({
refineCoreProps: {
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({
refineCoreProps: {
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({
refineCoreProps: {
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({
refineCoreProps: {
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({
refineCoreProps: {
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({
refineCoreProps: {
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({
refineCoreProps: {
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({
refineCoreProps: {
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({
refineCoreProps: {
action: "create",
resource: "post",
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.
  • 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({
refineCoreProps: {
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({
refineCoreProps: {
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({
refineCoreProps: {
queryOptions: {
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({
refineCoreProps: {
queryOptions: {
retry: 3,
},
},
});

warnWhenUnsavedChanges

Default: false

When it's true, Shows a warning when the user tries to leave the page with unsaved changes. It can be used to prevent the user from accidentally leaving the page.

It can be set globally in refine config.

useForm({
refineCoreProps: {
warnWhenUnsavedChanges: true,
},
});

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({
refineCoreProps: {
liveMode: "auto",
},
});

onLiveEvent

The callback function that is executed when new events from a subscription are arrived.

useForm({
refineCoreProps: {
onLiveEvent: (event) => {
console.log(event);
},
},
});

liveParams

Params to pass to liveProvider's subscribe method.

Return Values

tip

All mantine useForm and core useForm return values also available in useForm.

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 {
refineCore: { 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 {
refineCore: { 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 {
refineCore: { 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 {
refineCore: { 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.

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 React from "react";
import { useInvalidate } from "@refinedev/core";
import { useForm } from "@refinedev/mantine";

const PostEdit = () => {
const invalidate = useInvalidate();

useForm({
refineCoreProps: {
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.

pages/user/create.tsx
import React from "react";
import { Create, useForm } from "@refinedev/mantine";
import { TextInput } from "@mantine/core";

const UserCreate: React.FC = () => {
const { saveButtonProps, getInputProps } = useForm({
initialValues: {
name: "",
surname: "",
},
transformValues: (values) => ({
fullName: `${values.name} ${values.surname}`,
}),
});

return (
<Create saveButtonProps={saveButtonProps}>
<form>
<TextInput
mt={8}
label="Name"
placeholder="Name"
{...getInputProps("name")}
/>
<TextInput
mt={8}
label="Surname"
placeholder="Surname"
{...getInputProps("surname")}
/>
</form>
</Create>
);
};

API Reference

Properties

It supports all the features of the useForm hook provided by @mantine/form. Also, we added the following return values.

refineCoreProps: You can define all properties provided by useForm here. You can see all of them in here.

For example, we can define the refineCoreProps property in the useForm hook as:

import { useForm } from "@refinedev/mantine";

const { ... } = useForm({
..., // @mantine/form's useForm props
refineCoreProps: {
resource: "posts",
redirect: false,
// @refinedev/core's useForm props
},
});

Return values

Returns all the return values of the useForm hook provided by @mantine/form. Also, we added the following return values.

refineCore: Returns all values returned by useForm. You can see all of them in here.

For example, we can access the refineCore return value in the useForm hook as:

import { useForm } from "@refinedev/react-hook-form";

const {
..., // @mantine/form's useForm return values
saveButtonProps,
refineCore: {
queryResult,
... // @refinedev/core's useForm return values
},
} = useForm({ ... });
PropertyDescriptionType
saveButtonPropsProps for a submit button{ disabled: boolean; onClick: (e: React.FormEvent<HTMLFormElement>) => void; }

Type Parameters

PropertyDesriptionTypeDefault
TDataResult data returned by the query function. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
TVariablesForm values for mutation function{}Record<string, unknown>
TTransformedForm values after transformation for mutation function{}TVariables
TSelectDataResult data returned by the select function. Extends BaseRecord. If not specified, the value of TData will be used as the default value.BaseRecordTData

Example

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