useCan
useCan uses the Access Control Provider's can function as the query function for TanStack Query's useQuery. It takes the parameters that can takes. It can also be configured with queryOptions for useQuery. Returns the result of useQuery.
Usageβ
import { useCan } from "@refinedev/core";
const { data } = useCan({
resource: "resource-you-ask-for-access",
action: "action-type-on-resource",
params: { foo: "optional-params" },
});
Performanceβ
As the number of points that check for access control in your app increases, the performance of your app may take a hit, especially if its access control involves remote endpoints. Caching the access control checks helps quite a bit, and since Refine uses TanStack Query, it can be easily done by confiruging the staleTime and cacheTime properties.
import { useCan } from "@refinedev/core";
// inside your component
const { data } = useCan({
resource: "resource-you-ask-for-access",
action: "action-type-on-resource",
params: { foo: "optional-params" } },
queryOptions: {
staleTime: 5 * 60 * 1000, // 5 minutes
}
});
Propertiesβ
resource requiredβ
Passes to Access Control Provider's can function's resource parameter
useCan({
resource: "resource-you-ask-for-access",
});
action requiredβ
Passes to Access Control Provider's can function's action parameter
useCan({
action: "resource-you-ask-for-access",
});
paramsβ
Passes to Access Control Provider's can function's params parameter
useCan({
params: { foo: "optional-params" },
});
queryOptionsβ
Query options for TanStack Query's useQuery.
useCan({
queryOptions: {
staleTime: 5 * 60 * 1000, // 5 minutes
},
});
Return valuesβ
useCan will return the Query result of TanStack Query's useQuery.
For example, if you want to check if the user can create a post based on the return value:
const App = (
<Refine
// ...
accessControlProvider={{
can: async ({ resource, action }) => {
if (resource === "post" && action === "create") {
return {
can: false,
reason: "Unauthorized",
};
}
return { can: true };
},
}}
/>
);
const MyComponent = () => {
const { data: canCreatePost } = useCan({
action: "create",
resource: "post",
});
console.log(canCreatePost); // { can: false, reason: "Unauthorized" }
};
API Referenceβ
Propertiesβ
| Property | Type | Description |
|---|---|---|
resource | | Resource name for API data interactions |
action οΉ‘ | | Intended action on resource |
params | | Parameters associated with the resource |
queryOptions | | TansSack Query's useQuery options |
Type Parametersβ
| Property | Description |
|---|---|
| CanResponse | Result data of the query HttpError |
Return valuesβ
| Description | Type |
|---|---|
Result of the TanStack Query's useQuery | QueryObserverResult<{ data: CanReturnType; }> |