# Refine 後台的即時更新

> Refine 的 liveProvider：別人修改資料時，列表、紀錄和儀表板會自動更新。支援 Refine 4 和 5、任何 UI 套件和任何 data provider。

Source: https://hibira.io/zh-tw/guides/refine

Refine 的 liveProvider：別人修改資料時，列表、紀錄和儀表板會自動更新。支援 Refine 4 和 5、任何 UI 套件和任何 data provider。

Package: @hibira-io/refine

- 設定 liveMode: "auto" 後，useList、useOne、useTable、useForm 和 useShow 會自動重新取得資料。
- 使用 private 頻道與你自己的授權端點；同一個資源上的 hooks 共用一個訂閱。
- publishLiveEvent() 在每次修改後從你的 API 送出事件，並可略過發起修改的那個分頁。

## 1. 安裝

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

## 2. 設定

```tsx
import { Refine } from '@refinedev/core';
import Pusher from 'pusher-js';
import { liveProvider } from '@hibira-io/refine';

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

export const App = () => (
  <Refine
    dataProvider={dataProvider}
    liveProvider={liveProvider(pusher, { channelPrefix: 'private-', publish: false })}
    options={{ liveMode: 'auto' }}
  />
);
```

## 3. 使用

```ts
import Pusher from 'pusher';
import { publishLiveEvent } from '@hibira-io/refine/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,
});

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

## 開始之前

- 私人頻道與 presence 頻道需要後端提供授權端點，用應用程式密鑰簽署訂閱，做法和 pusher-js 相同。
- Laravel 也能送出相同的事件：在 resources.posts 廣播「refine」事件，內容格式同 Refine 的 LiveEvent。

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