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

useCreate

useCreate is an extended version of TanStack Query's useMutation. It supports all the features of useMutation and adds some extra features.

  • It uses the create method as the mutation function from the dataProvider which is passed to <Refine>.

It is useful when you want to create a new record.

Basic Usage

The useCreate hook returns many useful properties and methods. One of them is the mutate method which expects values and resource as parameters. These parameters will be passed to the create method from the dataProvider as parameters.

import { useCreate } from "@pankod/refine-core";

const { mutate } = useCreate();

mutate({
resource: "products",
values: {
name: "New Product",
material: "Wood",
},
});

Realtime Updates

This feature is only available if you use a Live Provider.

When the useCreate mutation runs successfully, it will call the publish method from liveProvider with some parameters such as channel, type etc. It is useful when you want to publish the changes to the subscribers on the client side.

Refer to the liveProvider documentation for more information

Invalidating Queries

When the useCreate mutation runs successfully, by default it will invalidate the following queries from the current resource: "list" and "many". That means, if you use useList or useMany hooks in the same page, they will refetch the data after the mutation is completed. You can change this behavior by passing invalidates prop.

Refer to the query invalidation documentation for more information

Audit Logs

This feature is only available if you use a Audit Log Provider.

When the useCreate mutation runs successfully, it will call the log method from auditLogProvider with some parameters such as resource, action, data etc. It is useful when you want to log the changes to the database.

Refer to the auditLogProvider documentation for more information

Properties

mutationOptions

mutationOptions is used to pass options to the useMutation hook. It is useful when you want to pass additional options to the useMutation hook.

Refer to the useMutation documentation for more information

useCreate({
mutationOptions: {
retry: 3,
},
});
tip

mutationOptions does not support onSuccess and onError props because they override the default onSuccess and onError functions. If you want to use these props, you can pass them to mutate functions like this:

const { mutate } = useCreate();

mutate(
{
resource: "products",
values: {
name: "New Product",
material: "Wood",
},
},
{
onError: (error, variables, context) => {
// An error occurred!
},
onSuccess: (data, variables, context) => {
// Let's celebrate!
},
},
);

Mutation Parameters

resource
required

It will be passed to the create method from the dataProvider as a parameter. The parameter is usually used as an API endpoint path. It all depends on how to handle the resource in the create method. See the creating a data provider section for an example of how resource are handled.

const { mutate } = useCreate();

mutate({
resource: "categories",
});

values
required

It will be passed to the create method from the dataProvider as a parameter. The parameter is usually used as the data to be created. It contains the data that will be sent to the server.

const { mutate } = useCreate();

mutate({
values: {
name: "New Category",
description: "New Category Description",
},
});

successNotification

NotificationProvider is required for this prop to work.

After data is fetched successfully, useCreate can call open function from NotificationProvider to show a success notification. With this prop, you can customize the success notification.

const { mutate } = useCreate();

mutate({
successNotification: (data, values, resource) => {
return {
message: `${data.title} Successfully fetched.`,
description: "Success with no errors",
type: "success",
};
},
});

errorNotification

NotificationProvider is required for this prop to work.

After data fetching is failed, useCreate will call open function from NotificationProvider to show an error notification. With this prop, you can customize the error notification.

const { mutate } = useCreate();

mutate({
errorNotification: (data, values, resource) => {
return {
message: `Something went wrong when getting ${data.id}`,
description: "Error",
type: "error",
};
},
});

metaData

metaData is used following two purposes:

  • To pass additional information to data provider methods.
  • Generate GraphQL queries using plain JavaScript Objects (JSON). Please refer GraphQL for more information.

In the following example, we pass the headers property in the metaData object to the create method. With similar logic, you can pass any properties to specifically handle the data provider methods.

const { mutate } = useCreate();

mutate({
metaData: {
headers: { "x-meta-data": "true" },
},
});

const myDataProvider = {
//...
create: async ({
resource,
variables,
metaData,
}) => {
const headers = metaData?.headers ?? {};
const url = `${apiUrl}/${resource}`;

//...
//...

const { data } = await httpClient.post(url, variables, { headers });

return {
data,
};
},
//...
};

dataProviderName

If there is more than one dataProvider, you can specify which one to use by passing the dataProviderName prop. It is useful when you have a different data provider for different resources.

const { mutate } = useCreate();

mutate({
dataProviderName: "second-data-provider",
});

invalidates

invalidates is used to specify which queries should be invalidated after the mutation is completed.

By default, it invalidates the following queries from the current resource: "list" and "many". That means, if you use useList or useMany hooks on the same page, they will refetch the data after the mutation is completed.

const { mutate } = useCreate();

mutate({
invalidates: ["list", "many"],
});

Return Values

Returns an object with TanStack Query's useMutation return values.

Refer to the useMutation documentation for more information

API

Mutation Parameters

PropertyDescriptionTypeDefault
resource
Required
Resource name for API data interactionsstring
values
Required
Values for mutation functionTVariables{}
successNotificationSuccessful Mutation notificationSuccessErrorNotification"Successfully created resource"
errorNotificationUnsuccessful Mutation notificationSuccessErrorNotification"There was an error creating resource (status code: statusCode)"
metaDataMetadata query for dataProviderMetaDataQuery{}
dataProviderNameIf there is more than one dataProvider, you should use the dataProviderName that you will use.stringdefault
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"]

Type Parameters

PropertyDesriptionTypeDefault
TDataResult data of the mutation. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
TVariablesValues for mutation function{}{}

Return value

DescriptionType
Result of the TanStack Query's useMutationUseMutationResult<
{ data: TData },
TError,
{ resource: string; values: TVariables; },
unknown>