@harelpls/use-pusher

中文文档
7.2.1发布于 2021/03/02MITTypeScriptESM + CJS近 30 天下载 9万

A wrapper around pusher-js for easy-as hooks in React.

原始使用文档
文档目录16 节
  1. API Reference/Docs
  2. Install
  3. Hooks
  4. Usage
  5. useChannel
  6. usePresenceChannel
  7. useEvent
  8. useTrigger
  9. usePusher
  10. Trigger Server
  11. useClientTrigger
  12. Typescript
  13. Testing
  14. React Native
  15. Contributing
  16. License

@harelpls/use-pusher

Easy as React hooks that integrate with the pusher-js library.

NPM Typed

API Reference/Docs

Install

yarn add @harelpls/use-pusher

Hooks

Usage

You must wrap your app with a PusherProvider and pass it config props for pusher-js initialisation.

import React from "react";
import { PusherProvider } from "@harelpls/use-pusher";

const config = {
  // required config props
  clientKey: "client-key",
  cluster: "ap4",

  // optional if you'd like to trigger events. BYO endpoint.
  // see "Trigger Server" below for more info
  triggerEndpoint: "/pusher/trigger",

  // required for private/presence channels
  // also sends auth headers to trigger endpoint
  authEndpoint: "/pusher/auth",
  auth: {
    headers: { Authorization: "Bearer token" },
  },
};

// Wrap app in provider
const App = () => {
  <PusherProvider {...config}>
    <Example />
  </PusherProvider>;
};

useChannel

Use this hook to subscribe to a channel.

// returns channel instance.
const channel = useChannel("channel-name");

usePresenceChannel

Augments a regular channel with member functionality.

const Example = () => {
  const { members, myID } = usePresenceChannel('presence-awesome');

  return (
    <ul>
      {Object.entries(members)
        // filter self from members
        .filter(([id]) => id !== myID)
        // map them to a list
        .map(([id, info]) => (
          <li key={id}>{info.name}</li>
        ))
      }
    </ul>
  )
}

useEvent

Bind to events on a channel with a callback.

const Example = () => {
  const [message, setMessages] = useState();
  const channel = useChannel("channel-name");
  useEvent(channel, "message", ({ data }) =>
    setMessages((messages) => [...messages, data])
  );
};

Note: This will bind and unbind to the event on each render. You may want to memoise your callback with useCallback before passing it in if you notice performance issues.

useTrigger

A helper function to create a server triggered event. BYO server (See Trigger Server below). Pass in triggerEndpoint prop to <PusherProvider />. Any auth headers from config.auth.headers automatically get passed to the fetch call.

import { useTrigger } from '@harelpls/use-pusher';

const Example = () => {.
  const trigger = useTrigger("channel-name");
  const handleClick = () =>
    trigger("event-name", "hello");

  return (
    <button onClick={handleClick}>Say Hello</button>
  )
}

usePusher

Get access to the Pusher instance to do other things.

import { usePusher } from "@harelpls/use-pusher";

const Example = () => {
  const { client } = usePusher();
  client.log("Look ma, logs!");

  return null;
};

Trigger Server

In order to trigger an event, you'll have to create a simple lambda (or an express server if that's your thing). Below is a short lambda that can handle triggered events from useTrigger.

import Pusher from "pusher";

const pusher = new Pusher({
  appId: "app-id",
  key: "client-key",
  secret: "mad-secret",
  cluster: "ap4",
});

export async function handler(event) {
  const { channelName, eventName, data } = JSON.parse(event.body);
  pusher.trigger(channelName, eventName, data);
  return { statusCode: 200 };
}

useClientTrigger

I don't want a server though

I hear ya. If you're feeling audacious, you can use client events to push directly from the client:

import { useChannel, useClientTrigger } from "@harelpls/use-pusher";

const Example = () => {
  const channel = useChannel("presence-ca");
  const trigger = useClientTrigger(channel);
  const handleClientEvent = () => {
    trigger("Pew pew");
  };

  return <button onClick={handleClientEvent}>Fire</button>;
};

Typescript

This project was built using typescript, so types are built-in. Yeeeew!

Testing

I've teamed up with @nikolalsvk on pusher-js-mock to bring y'all a great pusher mock.

Testing emitted events with jest can be achieved using jest.mock and @testing-library/react (or enzyme, though your tests should reflect what the user should see NOT how the component handles events internally):

// Example.tsx
import React from "react";
import { useChannel, useEvent } from "@harelpls/use-pusher";

const Example = () => {
  const [title, setTitle] = useState();
  const channel = useChannel("my-channel");
  useEvent(channel, "title", ({ data }) => setTitle(data));

  return <span>{title}</span>;
};

// Example.test.tsx
import { render, act } from "@testing-library/react";
import { PusherMock, PusherChannelMock } from "pusher-js-mock";

// mock out the result of the useChannel hook
const mockChannel = new PusherChannelMock();
jest.mock("@harelpls/use-pusher", () => ({
  ...require.requireActual("@harelpls/use-pusher"),
  useChannel: () => mockChannel,
}));

test("should show a title when it receives a title event", async () => {
  // mock the client
  const client = new PusherMock("client-key", { cluster: "ap4" });

  // render component and provider with a mocked context value
  const { findByText } = render(
    <PusherProvider clientKey="client-key" cluster="ap4" value={{ client }}>
      <Example />
    </PusherProvider>
  );

  // emit an event on the mocked channel
  act(() => mockChannel.emit("title", { data: "Hello world" }));

  // assert expectations
  expect(await findByText("Hello world")).toBeInTheDocument();
});

Check out the example tests for testing presence channels.

React Native

This package comes with React Native support. Import your PusherProvider from @harelpls/use-pusher/react-native instead of the default @harelpls/use-pusher. All exports are re-exported from there.

Ensure you add the netinfo package to your project too: @react-native-community/netinfo.

import { PusherProvider, useChannel } from "@harelpls/use-pusher/react-native";

Contributing

  1. Clone the repository and run yarn && yarn test:watch
  2. Get coding!

Please write tests (100% jest coverage) and types.

License

MIT © @mayteio


This hook is created using create-react-hook.

版本与发布记录

@harelpls/use-pusher 共发布 29 个版本,首次发布于 2020/01/21;过去 12 个月发布了 0 个版本。

版本发布日期距今
7.2.1latest2021/03/025 年前
7.1.02020/09/186 年前
7.0.02020/08/196 年前
6.0.32020/08/196 年前
6.0.22020/07/236 年前
6.0.12020/07/226 年前

其他发布通道:beta → 4.1.4。

关于 @harelpls/use-pusher 的常见问题

@harelpls/use-pusher 是什么?

A wrapper around pusher-js for easy-as hooks in React.

如何安装 @harelpls/use-pusher?

在项目目录运行 npm install @harelpls/use-pusher,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^16.9.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@harelpls/use-pusher 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@harelpls/use-pusher 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@harelpls/use-pusher 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=8。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@harelpls/use-pusher 可以商用吗?

@harelpls/use-pusher 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@harelpls/use-pusher 的下载量有多少?

根据 npm 官方下载统计,@harelpls/use-pusher 在 2026/10/17 – 2026/11/15 这 30 天内被下载 90,345 次,日均约 3,012 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@harelpls/use-pusher 还在维护吗?

最新版本 7.2.1 发布于 2021/03/02(5 年前);至今共发布 29 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/01/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。