跳到主要内容

useCreate

useCreate is a modified version of react-query's useMutation for create mutations.

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

Features

Usage

Let'say we have a resource named categories

https://api.fake-rest.refine.dev/categories
{
[
{
id: 1,
title: "E-business",
},
{
id: 2,
title: "Virtual Invoice Avon",
},
{
id: 3,
title: "Unbranded",
},
];
}
type CategoryMutationResult = {
id: number;
title: string;
};

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

const { mutate } = useCreate<CategoryMutationResult>();

mutate({
resource: "categories",
values: {
title: "New Category",
},
});
提示

mutate can also accept lifecycle methods like onSuccess and onError.

mutate(
{
resource: "categories",
values: {
title: "New Category",
},
},
{
onError: (error, variables, context) => {
// An error happened!
},
onSuccess: (data, variables, context) => {
// Let's celebrate!
},
},
);

Refer to react-query docs for further information.

After the mutation runs, categories will be updated as below:

https://api.fake-rest.refine.dev/categories
{
[
{
id: 1,
title: "E-business",
},
{
id: 2,
title: "Virtual Invoice Avon",
},
{
id: 3,
title: "Unbranded",
},
{
id: 4,
title: "New Category",
},
];
}
备注

Queries that use /categories endpoint will be automatically invalidated to show the updated data. For example, data returned from useList will be automatically updated.

提示

useCreate returns react-query's useMutation result which includes a lot properties, one of which being mutate.

警告

Variables passed to mutate must have these types.

{
resource: string;
values: TVariables = {};
}

API

Properties

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 react-query's useMutationUseMutationResult<
{ data: TData },
TError,
{ resource: string; values: TVariables; },
unknown>