# Refine 后台的实时更新

> Refine 的 liveProvider：别人修改数据时，列表、记录和仪表盘会自动更新。支持 Refine 4 和 5、任何 UI 套件和任何 data provider。

Source: https://hibira.io/zh-cn/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)
