跳到主要内容

useCustomMutation

useCustomMutation is a modified version of react-query's useMutation for custom mutations.

It uses the custom method from the dataProvider which is passed to <Refine>.

attention

useCustomMutation should not be used when creating, updating or deleting a resource. To do these; useCreate, useUpdate or useDelete hooks should be used instead.

This is because useCustomMutation, unlike other data hooks, does not invalidate queries and therefore will not update the application state either.

If you need to custom query request, use the useCustom hook.

Features

  • You can send a request to any link, using any of the methods (post, put, patch, delete).

Usage

Let's create a new category using useCustomMutation as a use case.

[POST] https://api.fake-rest.refine.dev/categories
{
"title": "New Category"
}
import { useCustomMutation, useApiUrl } from "@pankod/refine-core";

interface ICategory {
id: number;
title: string;
}

const apiUrl = useApiUrl();

const { mutate } = useCustomMutation<ICategory>();
mutate({
url: `${API_URL}/categories`,
method: "post",
values: {
title: "New Category",
},
});
提示

mutate can also accept lifecycle methods like onSuccess and onError.

mutate(
{
url: `${API_URL}/categories`,
method: "post",
values: {
title: "New Category",
},
config: {
headers: {
"x-custom-header": "foo-bar",
},
},
},
{
onError: (error, variables, context) => {
// An error happened!
},
onSuccess: (data, variables, context) => {
// Let's celebrate!
},
},
);

Refer to react-query docs for further information.

API

Properties

PropertyDescriptionType
url
Required
URLstring
method
Required
Methodpost, put, patch, delete
successNotificationSuccessful Mutation notificationSuccessErrorNotification
errorNotificationUnsuccessful Mutation notificationSuccessErrorNotification
metaDataMetadata query for dataProviderMetaDataQuery
dataProviderNameIf there is more than one dataProvider, you should use the dataProviderName that you will use.string
configThe config of your request. You can send headers, payload, query, filters and sort using this field.{ sort?: CrudSorting; filters?: CrudFilters; payload?: {}; query?: {}, headers?: {}; }

Type Parameters

PropertyDesriptionTypeDefault
TDataResult data of the query. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
TQueryValues for query params.TQueryunknown
TPayloadValues for params.TPayloadunknown

Return value

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