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

useOne

useOne is an extended version of TanStack Query's useQuery that supports all of its features and adds some more.

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

  • It uses a query key to cache the data. The query key is generated from the provided properties. You can see the query key by using the TanStack Query devtools.

It is useful when you want to fetch a single record from the API. It will return the data and some functions to control the query.

Basic Usage​

The useOne hook expects a resource and id property, which will be passed to the getOne method from the dataProvider as a parameter.

When these properties are changed, the useOne hook will trigger a new request.

http://localhost:3000/products
import { useState } from "react";
import { useOne, HttpError } from "@refinedev/core";

interface IProduct {
id: number;
name: string;
material: string;
}

const ProductList: React.FC = () => {
const [id, setId] = useState(1);

const { data, isLoading, isError } = useOne<IProduct, HttpError>({
resource: "products",
id,
});

const product = data?.data;

if (isLoading) {
return <div>Loading...</div>;
}

if (isError) {
return <div>Something went wrong!</div>;
}

return (
<div>
<h3>Product Details</h3>
<p>id: {product?.id}</p>
<p>name: {product?.name}</p>
<p>material: {product?.material}</p>

<br />

<button
onClick={() => setId((prev) => prev - 1)}
disabled={id === 1}
>
{"<"} Prev Product
</button>
<button onClick={() => setId((prev) => prev + 1)}>
Next Product {">"}
</button>
</div>
);
};

Realtime Updates​

caution

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

When the useOne hook is mounted, it will call the subscribe method from the liveProvider with some parameters such as channel, resource etc. It is useful when you want to subscribe to live updates.

For more information, refer to the liveProvider documentation→

Properties​

resource
required
​

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

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

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

id
required
​

This prop will be passed to the getMany method from the dataProvider as a parameter. It is used to determine which records to fetch.

useOne({
id: 123,
});

dataProviderName​

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

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

queryOptions​

queryOptions is used to pass additional options to the useQuery hook. It is useful when you want to pass additional options to the useQuery hook.

useOne({
queryOptions: {
retry: 3,
enabled: false,
},
});

For more information, refer to the useQuery documentation→

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 create method. With similar logic, you can pass any properties to specifically handle the data provider methods.

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

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

//...
//...

const { data } = await httpClient.get(`${url}`, { headers });

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

For more information, refer to the meta section of the General Concepts documentation→

successNotification​

caution

NotificationProvider is required for this prop to work.

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

useOne({
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.

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

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

liveMode​

caution

LiveProvider is required for this prop to work.

Determines 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 the Live / Realtime page.

useOne({
liveMode: "auto",
});

For more information, refer to the Live / Realtime page→

onLiveEvent​

caution

LiveProvider is required for this prop to work.

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

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

liveParams​

caution

LiveProvider is required for this prop to work.

Params to pass to liveProvider's subscribe method.

Return Values​

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

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

API​

Properties​

Type Parameters​

PropertyDesriptionTypeDefault
TQueryFnDataResult data returned by the query function. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
TDataResult data returned by the select function. Extends BaseRecord. If not specified, the value of TQueryFnData will be used as the default value.BaseRecordTQueryFnData

Return values​

DescriptionType
Result of the TanStack Query's useQueryQueryObserverResult<{ data: TData; }>