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

useUpdate

useUpdate is used when you want to update a record. It is an extended version of TanStack Query's useMutation that supports all of its features and adds some more.

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

Basic Usage​

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

import { useUpdate } from "@refinedev/core";

const { mutate } = useUpdate();

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

Realtime Updates​

caution

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

When the useUpdate 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.

For more information, refer to the liveProvider documentation→

Invalidating Queries​

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

For more information, refer to the query invalidation documentation→

Audit Logs​

caution

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

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

For more information, refer to the auditLogProvider documentation→

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.

useUpdate({
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 } = useUpdate();

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

Refer to the useMutation documentation for more information β†’

Mutation Parameters​

resource
required
​

This parameter will be passed to the update method from the dataProvider as a parameter. It is usually used as an API endpoint path but it all depends on how you handle the resource in the update method.

const { mutate } = useUpdate();

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

For more information, refer to the creating a data provider tutorial β†’

id
required
​

This prop will be passed to the update method from the dataProvider as a parameter. It is used to determine which record to update.

const { mutate } = useUpdate();

mutate({
id: 123,
});

values
required
​

This prop will be passed to the update method from the dataProvider as a parameter. It is usually used as the data to be updated and contains the data that will be sent to the server.

const { mutate } = useUpdate();

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

mutationMode​

Mutation mode determines which mode the mutation runs with. Mutations can run under three different modes: pessimistic, optimistic, and undoable. The default mode is pessimistic. Each mode corresponds to a different type of user experience.

const { mutate } = useUpdate();

mutate({
mutationMode: "undoable",
});

For more information, refer to the mutation mode documentation β†’

undoableTimeout​

When mutationMode is set to undoable, undoableTimeout is used to determine the duration to wait before executing the mutation. The default value is 5000 milliseconds.

const { mutate } = useUpdate();

mutate({
mutationMode: "undoable",
undoableTimeout: 10000,
});

onCancel​

When mutationMode is set to undoable, onCancel is used to determine what to do when the user cancels the mutation.

const { mutate } = useUpdate();

mutate({
mutationMode: "undoable",
onCancel: (cancelMutation) => {
cancelMutation();
// you can do something else here
},
});

successNotification​

caution

NotificationProvider is required for this prop to work.

This prop allows you to customize the success notification that shows up when the data is fetched successfully and useUpdate can calls open function from NotificationProvider:

const { mutate } = useUpdate();

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

errorNotification​

caution

NotificationProvider is required for this prop to work.

This prop allows you to customize the error notification that shows up when the data fetching fails and the useUpdate calls the open function from NotificationProvider:

const { mutate } = useUpdate();

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

meta​

meta is a special property that can be used to pass additional information to data provider methods for the following purposes:

  • Customizing the data provider methods for specific use cases.
  • Generating GraphQL queries using plain JavaScript Objects (JSON).

In the following example, we pass the headers property in the meta object to the update method. You can pass any properties to specifically handle the data provider methods with similar logic.

const { mutate } = useUpdate();

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

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

//...
//...

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

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

Refer to the meta section of the General Concepts documentation for more information β†’

dataProviderName​

This prop allows you to specify which dataProvider if you have more than one. Just pass it like in the example:

const { mutate } = useUpdate();

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", "many" and "detail". That means, if you use useList, useMany, or useOne hooks on the same page, they will refetch the data after the mutation is completed.

const { mutate } = useUpdate();

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

Return Values​

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

For more information, refer to the useMutation documentation β†’

API​

Mutation Parameters​

PropertyDescriptionTypeDefault
resource
Required
Resource name for API data interactionsstring
id
Required
id for mutation functionBaseKey
values
Required
Values for mutation functionTVariables{}
mutationModeDetermines when mutations are executed "pessimistic | "optimistic | "undoable""pessimistic"*
undoableTimeoutDuration to wait before executing the mutation when mutationMode = "undoable"number5000ms*
onCancelCallback that runs when undo button is clicked on mutationMode = "undoable"(cancelMutation: () => void) => void
successNotificationSuccessful Mutation notificationSuccessErrorNotification"Successfully updated resource"
errorNotificationUnsuccessful Mutation notificationSuccessErrorNotification"Error when updating resource (status code: statusCode)"
metaMeta data 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", "detail"]
note

These props have default values in RefineContext and can also be set on <Refine> component. useUpdate will use what's passed to <Refine> as default, but a local value will override it.


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; id: BaseKey; values: TVariables; },
UpdateContext>
*

* UpdateContext is an internal type.