Skip to content

Commit cf706ce

Browse files
committed
improve useCanAccess
1 parent f4500f4 commit cf706ce

1 file changed

Lines changed: 15 additions & 2 deletions

File tree

docs/useCanAccess.md

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ title: "useCanAccess"
77

88
This hook, part of [the ra-rbac module](https://marmelab.com/ra-enterprise/modules/ra-rbac)<img class="icon" src="./img/premium.svg" />, calls the `authProvider.getPermissions()` to get the role definitions, then checks whether the requested action and resource are allowed for the current user.
99

10+
## Usage
11+
1012
`useCanAccess` takes an object `{ action, resource, record }` as argument. It returns an object describing the state of the RBAC request. As calls to the `authProvider` are asynchronous, the hook returns a `loading` state in addition to the `canAccess` key.
1113

1214
```jsx
@@ -15,8 +17,8 @@ import { useRecordContext, DeleteButton } from 'react-admin';
1517

1618
const DeleteUserButton = () => {
1719
const record = useRecordContext();
18-
const { loading, canAccess } = useCanAccess({ action: 'delete', resource: 'users', record });
19-
if (loading || !canAccess) return null;
20+
const { isLoading, canAccess } = useCanAccess({ action: 'delete', resource: 'users', record });
21+
if (isLoading || !canAccess) return null;
2022
return <DeleteButton record={record} resource="users" />;
2123
};
2224
```
@@ -57,3 +59,14 @@ const { canAccess: canReadSelfSales } = useCanAccess({ action: "read", resource:
5759
**Tip**: The *order* of permissions as returned by the `authProvider` isn't significant. As soon as at least one permission grants access to an action on a resource, the user will be able to perform it.
5860

5961
**Tip**: `useCanAccess` is asynchronous, because it calls `usePermissions` internally. If you have to use `useCanAccess` several times in a component, the rendered result will "blink" as the multiple calls to `authProvider.getPermissions()` resolve. To avoid that behavior, you can use the `usePermissions` hook once, then call [the `canAccess` helper](./canAccess.md).
62+
63+
## Parameters
64+
65+
`useCanAccess` expects a single parameter object with the following properties:
66+
67+
| Name | Required | Type | Default | Description |
68+
| --- | --- | --- | --- | --- |
69+
| `resource` | Required | `string` | - | The resource to check, e.g. 'users', 'comments', 'posts', etc. |
70+
| `action` | Required | `string` | - | The action to check, e.g. 'read', 'list', 'export', 'delete', etc. |
71+
| `record` | Optional | `object` | - | The record to check. If passed, the child only renders if the user has permissions for that record, e.g. `{ id: 123, firstName: "John", lastName: "Doe" }` |
72+

0 commit comments

Comments
 (0)