Phoenix Sockets, Channels, and Presence with React hooks.
Installation:
$ npm install phoenix-hooks
import { useSocket } from 'phoenix-hooks'
const { socket, socketState } = useSocket(`//localhost:4000/socket`, {params: {userToken: "<token value>"}})
url
:string
wss://localhost:4000/socket
ws://localhost:4000/socket
localhost:4000/socket
/socket
opts
:SocketOptions
type SocketOptions = {
binaryType: BinaryType;
params: object | (() => object);
transport: string;
timeout: number;
heartbeatIntervalMs: number;
longpollerTimeout: number;
encode: (payload: object, callback: (encoded: any) => void) => void;
decode: (payload: string, callback: (decoded: any) => void) => void;
logger: (kind: string, message: string, data: any) => void;
reconnectAfterMs: (tries: number) => number;
rejoinAfterMs: (tries: number) => number;
vsn: string;
onOpen: () => void;
onClose: () => void;
onError: (any) => void;
}
enum SocketStates {
UNINSTANTIATED = -1,
CONNECTING,
OPEN,
CLOSING,
CLOSED,
}
Enum representing the socket state.
The underlying Phoenix Socket class.
Disconnect to the socket.
<button onClick={() => socketDisconnect()}>Disconnect</button>
Connect to the socket. useSocket
will start the socket for you so this may not be needed; use for explicitly reconnecting after using socketDisconnect
.
<button onClick={() => socketConnect()}>Connect</button>
Handle callback on each message received
useEffect(() => {
socketHandleMessage(message => {
console.log('socketHandleMessage', message)
})
}, [socketHandleMessage])
import { useChannels } from 'phoenix-hooks'
const { socket } = useSocket(`//localhost:4000/socket`) // Optional, see Provider
const { handleChannelEvent, pushChannelEvent } =
useChannels(`chat:${123}`, {onJoin: params => {
// Use params set join/3 response
}})
Connect to a given Phoenix channel.
channelName
:string
opts
:ChannelOptions
type ChannelOptions = {
onClose?: () => void;
onError?: (err: any) => void;
onLeave?: () => void;
onJoin?: (object) => void; // Useful for getting join/3 response
onTimeout?: () => void;
socket: Socket;
params: object;
}
enum ChannelStates {
CLOSED,
ERRORED,
JOINED,
JOINING,
LEAVING
}
Enum representing the connection status to a channel. JOINED
is the "everything is fine here" state.
The underlying Phoenix Channel class.
Handle callback for a specific channel event
useEffect(() => {
handleChannelEvent("selection", response => {
console.log('handleChannelEvent', response)
})
}, [socketHandleMessage])
Push an event with a payload. Phoenix handles via handle_in/3
Leave the channel
import { useSocket, useChannels, usePresence } from 'phoenix-hooks'
const { socket } = useSocket(`//localhost:4000/socket`) // Optional, see Provider
const { channel } = useChannels(`chat:${123}`, {socket: socket})
const { handlePresenceSync } = usePresence(channel)
Use Phoenix Presence for a given channel.
channel
:Channel
Channel from a previoususeChannels
call
The underlying Phoenix Presence class.
Handle callback on sync.
const [editors, setEditors] = useState([])
useEffect(() => {
handlePresenceSync(users => {
setEditors(users.sort((u1, u2) => {
return u1.metas[0].online_at > u2.metas[0].online_at
}))
})
}, [handlePresenceSync])
Handle callback upon presence_diff
join
Handle callback upon presence_diff
leave
import { PhoenixSocketProvider } from 'phoenix-hooks'
function App() {
return (
<PhoenixSocketProvider url={`//localhost:4000/socket`}>
{/* Your component */}
</PhoenixSocketProvider>
)
}
url
:string
wss://localhost:4000/socket
ws://localhost:4000/socket
localhost:4000/socket
/socket
opts
:SocketOptions
type SocketOptions = {
binaryType: BinaryType;
params: object | (() => object);
transport: string;
timeout: number;
heartbeatIntervalMs: number;
longpollerTimeout: number;
encode: (payload: object, callback: (encoded: any) => void) => void;
decode: (payload: string, callback: (decoded: any) => void) => void;
logger: (kind: string, message: string, data: any) => void;
reconnectAfterMs: (tries: number) => number;
rejoinAfterMs: (tries: number) => number;
vsn: string;
onOpen: () => void;
onClose: () => void;
onError: (any) => void;
}