useEventMessages
Introduction
This hook is created to listen to ALL events received from the server.
If you intend to send
events to the server, we recommend choosing the
useEmitter
hook.
Initialization
const { data, timestamp, connected, connecting, onEvent, onError, onReconnecting } = useEventMessages(onChatMessage);
How it works?
useEventMessages
hooks into Socket adapter and start listening to given event when a component is mounted. It uses
dependency tracking to limit re-rendering and help with performance.
Under the hood, communication with the core systems is established by event emitters. There are many "helper hooks"
that get returned from the hook, like onEvent
, onError
, and onReconnecting
(among others). They will help you
handle various events in the lifecycle of sockets communication.
We used this approach to avoid overloading the base hook with callback logic, which causes low code readability and increases complexity.
import { useEventMessages } from "@hyper-fetch/react";
import { onChatMessage } from "server";
const UsersListPage: React.FC = () => {
const [messages, setMessages] = useState([])
const { data, connected, connecting, onEvent, onError, onReconnecting } = useEventMessages(onChatMessage);
onEvent(({ data: message }) => {
setMessages((prev) => [...prev, message]); // [ MessageType, MessageType, MessageType ]
});
onError((error) => {
console.log(error); // Error Event
});
onReconnecting((reconnectingAttempt) => {
console.log(reconnectingAttempt); // 1
})
if(error && !connecting) {
return <Alert severity="error">{error.message}</Alert>
}
return (
<div>
{connecting && <Loader>}
{!messages.length && <div>No messages</div>}
{!messages.length && <div>{messages.map(message => <div>{message}</div>)}</div>}
</div>
);
};
Options
Configuration options for useEventMessages
must be provided as the second parameter.
const { ... } = useEventMessages(listener, options)
{
dependencyTracking: boolean;
filter: (data: ResponsesType, event: MessageEvent<ResponsesType>) => boolean | string[];
}
Returns
Returned values from this hook.
const values = useEventMessages(listener);
{
connected: boolean;
connecting: boolean;
data: unknown;
onClose: (callback: VoidFunction) => void;
onConnecting: (callback: VoidFunction) => void;
onError: (callback: (event: ErrorType) => void) => void;
onEvent: (callback: (data: ResponsesType, event: MessageEvent<ResponsesType>) => void) => void;
onOpen: (callback: VoidFunction) => void;
onReconnecting: (callback: (attempts: number) => void) => void;
onReconnectingStop: (callback: (attempts: number) => void) => void;
setConnected: (connected: boolean) => void;
setConnecting: (connecting: boolean) => void;
setData: (data: unknown) => void;
setTimestamp: (timestamp: number) => void;
timestamp: number;
}