use-pusher
Easy as hooks that integrate with the pusher-js library.
@harelpls/use-pusher
- please update your dependencies!
⚠️ this package has moved to 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.
;; ; // Wrap app in provider;
useChannel
Use this hook to subscribe to a channel.
// returns channel instance.;
usePresenceChannel
Augments a regular channel with member functionality.
useEvent
Bind to events on a channel with a callback.
;
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.
;
usePusher
Get access to the Pusher instance to do other things.
; ;
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
.
; ;
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:
; ;
Typescript
This project was built using typescript, so types are built-in. Yeeeew!
Testing
Typed PusherMock
, PusherChannelMock
and PusherPresenceChannelMock
utils are provided based on pusher-js-mock
(thanks mate 🙏). Use these to stub out the client and channels, with an additional emit
method on the channel classes.
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;; ; // Example.test.tsx;; // mock out the result of the useChannel hook;jest.mock'@harelpls/use-pusher',; test'should show a title when it receives a title event', ;
Check out the example tests for testing presence channels.
Contributing
- Clone the repository and run
yarn && yarn test:watch
- Get coding!
Please write tests (100% jest coverage) and types.
License
MIT © @mayteio
This hook is created using create-react-hook.