use-phoenix-channel
A React hook that allows for responding to and broadcasting messages over Phoenix channels.
See the "Improving UX with Phoenix Channels & React Hooks" Blogpost for an example use case.
npm install use-phoenix-channel
// or
yarn add use-phoenix-channel
There are two main pieces to the libray, the SocketProvider
Component and the useChannel
hook.
SocketProvider
Component
To be used once at a high level in the component tree similar to Redux Provider:
const Root = { return <SocketProvider wsUrl='localhost:4000/socket' options= token > <App /> </SocketProvider> }
useChannel
Hook
const MyComponent = { const state broadcast = // ...}
The useChannel hook gives a component access to state that will update in real time in response to messages broadcast over a channel. It also gives a component access to a function to broadcast messages over the specified channel.
It should be passed the name of the channel, a reducer function defining the messages to respond to and any initial state.
Responding to Messages
const channelName = 'counter:example'const countReducer = { // the second argument is the message sent over the channel // it will contain an event key and a payload key }const initialState = 0 const MyComponent = { const count broadcast = return <div> <h1>`The value below will update in realtime as the count is changed by other subscribers to the {channelName} channel`</h1> count </div> }
Broadcasting Messages
The broadcast function returned by the hook can be invoked to push messages onto the channel. It should be passed the event name and a payload.
const MyComponent = { const state broadcast = return <div> <button onClick= > `Increment by ` <button /> <button onClick= > `Decrement by ` <button /> </div> }