# react-admin 即時功能：列表自動更新、誰在看、編輯鎖

> 免費開源：列表和資料會自己更新，看得到還有誰開著同一筆資料，而且同一時間只有一個人能編輯。支援 react-admin 5、React 18 和 19，任何 data provider 都能用。

Source: https://hibira.io/zh-tw/guides/react-admin

免費開源：列表和資料會自己更新，看得到還有誰開著同一筆資料，而且同一時間只有一個人能編輯。支援 react-admin 5、React 18 和 19，任何 data provider 都能用。

Package: @hibira-io/react-admin

- <LiveRefresh /> 會在有人改資料時，重新抓列表、資料和關聯資料。
- <RecordViewers /> 顯示還有誰開著這筆資料；<RecordLockGuard> 在別人編輯時把表單設成唯讀，不需要另外建鎖定資料表。
- <LiveRecord /> 在資料被別人存檔或刪除時提醒正在編輯的人；<NewRecordsBadge /> 在選單上顯示新資料數量。

## 1. 安裝

```shell
npm install @hibira-io/react-admin pusher-js
# on your backend
npm install pusher
```

## 2. 設定

```tsx
import { Admin, Edit, List, Resource, SimpleForm } from 'react-admin';
import Pusher from 'pusher-js';
import { addRealtimeMethods, LiveRecord, LiveRefresh, RecordLockGuard, RecordViewers } from '@hibira-io/react-admin';

const pusher = new Pusher(import.meta.env.VITE_HIBIRA_KEY, {
  cluster: 'hkg',
  wsHost: 'ws.hibira.io',
  channelAuthorization: { endpoint: '/api/hibira/auth', transport: 'ajax' },
});
const realtime = addRealtimeMethods(dataProvider, pusher, { channelPrefix: 'private-' });

const OrderList = () => <List><LiveRefresh />{/* ... */}</List>;
const OrderEdit = () => (
  <Edit actions={<RecordViewers />}>
    <LiveRecord />
    <RecordLockGuard><SimpleForm>{/* ... */}</SimpleForm></RecordLockGuard>
  </Edit>
);

export const App = () => (
  <Admin dataProvider={realtime}>
    <Resource name="orders" list={OrderList} edit={OrderEdit} />
  </Admin>
);
```

## 3. 使用

```ts
import Pusher from 'pusher';
import { authorizeChannel, publishResourceEvent } from '@hibira-io/react-admin/server';

const pusher = new Pusher({
  appId: process.env.HIBIRA_APP_ID!,
  key: process.env.HIBIRA_KEY!,
  secret: process.env.HIBIRA_SECRET!,
  host: 'ws.hibira.io',
  useTLS: true,
});

// POST /api/hibira/auth, after checking the session: signs private and presence channels
authorizeChannel(pusher, socketId, channelName, { id: user.id, fullName: user.name });

// after updating order 42
await publishResourceEvent(pusher, { resource: 'orders', type: 'updated', ids: [42] }, { channelPrefix: 'private-', socketId: req.headers['x-socket-id'] });
```

## 開始之前

- 私人頻道與 presence 頻道需要後端提供授權端點，用應用程式密鑰簽署訂閱，做法和 pusher-js 相同。
- 編輯鎖屬於最先打開資料的人，對方一離開就換下一個人。presence 無法使用時不會上鎖。

- [npm](https://www.npmjs.com/package/@hibira-io/react-admin)
- [GitHub](https://github.com/hibira-io/react-admin)
