# Cập nhật trực tiếp trong Qwik

> Chỉ kết nối tới Hibira từ component Qwik khi nó hiển thị, để pusher-js không nằm trong lần tải đầu, và ký kênh riêng tư trong một endpoint Qwik City.

Source: https://hibira.io/vi/guides/qwik

Chỉ kết nối tới Hibira từ component Qwik khi nó hiển thị, để pusher-js không nằm trong lần tải đầu, và ký kênh riêng tư trong một endpoint Qwik City.

Package: pusher-js

- useVisibleTask$ tải pusher-js khi cần và ngắt kết nối khi cleanup.
- Một endpoint onPost của Qwik City ký kênh riêng tư và presence bằng gói pusher trên npm.

## 1. Cài đặt

```shell
npm install pusher-js pusher
```

## 2. Sử dụng

```tsx
import { component$, useSignal, useVisibleTask$ } from '@builder.io/qwik';

export default component$(() => {
  const status = useSignal('Waiting for updates');
  useVisibleTask$(async ({ cleanup }) => {
    const { default: Pusher } = await import('pusher-js');
    const pusher = new Pusher(import.meta.env.PUBLIC_HIBIRA_APP_KEY, {
      cluster: 'hkg',
      wsHost: 'ws.hibira.io',
      channelAuthorization: { endpoint: '/api/hibira/auth', transport: 'ajax' },
    });
    pusher.subscribe('orders').bind('order.shipped', (o: { id: number }) => (status.value = `Order #${o.id} shipped`));
    cleanup(() => pusher.disconnect());
  });
  return <p>{status.value}</p>;
});
```

## 3. Ký đăng ký kênh

```ts
// src/routes/api/hibira/auth/index.ts
import type { RequestHandler } from '@builder.io/qwik-city';
import Pusher from 'pusher';

export const onPost: RequestHandler = async ({ parseBody, env, json }) => {
  const pusher = new Pusher({
    appId: env.get('HIBIRA_APP_ID')!, key: env.get('HIBIRA_APP_KEY')!, secret: env.get('HIBIRA_APP_SECRET')!,
    host: 'ws.hibira.io', port: '443', useTLS: true,
  });
  const form = (await parseBody()) as Record<string, string>;
  // check the signed-in user may join this channel first
  json(200, pusher.authorizeChannel(form.socket_id, form.channel_name));
};
```

## Trước khi bắt đầu

- Với gói Free, hãy thêm mọi origin mà trang của bạn tải từ đó vào Origin được phép của ứng dụng (http://localhost:3000 khi phát triển, sau đó là tên miền của bạn). "*" cần gói trả phí.
- Secret của ứng dụng chỉ hiện một lần, khi bạn tạo ứng dụng hoặc xoay vòng secret. Hãy giữ nó trên máy chủ, không bao giờ đưa vào trình duyệt hay bản build game.

- [npm](https://www.npmjs.com/package/pusher-js)
- [npm](https://www.npmjs.com/package/pusher)
