useEmitter
The useEmitter
hook is your main tool for sending events to a server in React components. It integrates seamlessly
with Hyper Fetch's core systems, particularly the Emitter
, to deliver a robust, reactive, and
efficient event-emitting experience.
- Declarative event emitting: Provide an
Emitter
and let the hook manage the process. - Automatic connection management: Handles
connected
state for you. - Lifecycle callbacks: Easily run side effects on events, errors, or reconnections.
- Deep core integration: Uses a central event dispatcher to send events.
If you intend to
listen
to events from the server, we recommend choosing theuseListener
hook.
Quick Start
To use useEmitter
, provide a prepared Emitter
instance. The hook returns an emit
function
to send events and the current state of the socket connection.
First, let's define an emitter.
// src/api/chat.ts
import { socketInstance } from "./socket";
export const emitMessage = socketInstance.createEmitter<ChatMessageType, AcknowledgementResponseType>()({
endpoint: "chat-message", // endpoint of the event
});
Now, let's use it in a component.
// src/components/MessageComponent.tsx
import { useEmitter } from "@hyper-fetch/react";
import { emitMessage } from "./api/chat";
const MessageComponent: React.FC = () => {
const { emit, connected } = useEmitter(emitMessage);
const onSubmit = (values: { message: string }) => {
// ResponseDataType is automatically inherited from Emitter class
const acknowledge = (error: Error, data: ResponseDataType) => {
if (error) {
alert("No server response!");
} else {
alert("Message received on server.");
}
};
emit({ data: values }, acknowledge);
};
return (
<Form onSubmit={onSubmit}>
{/* ... form fields ... */}
<button type="submit" disabled={!connected}>
Send
</button>
</Form>
);
};
Event Handlers
To handle side effects such as notifications, logging, or triggering other actions, useEmitter
provides a set of event
handler hooks. This keeps your component's rendering logic clean and separates side effects from state management.
onEvent
: Fires before we send event message.onError
: Fires when an error occurs.onReconnecting
: Fires when the socket is attempting to reconnect.
import { useEmitter } from "@hyper-fetch/react";
import { emitMessage } from "./api";
const MessageComponent: React.FC = () => {
const { emit, onEvent, onError, onReconnecting } = useEmitter(emitMessage);
onEvent((emitter) => {
// Event before we send event message
console.log(emitter); // Emitter instance
});
onError((error) => {
console.log(error); // Error Event
});
onReconnecting((reconnectingAttempt) => {
console.log(reconnectingAttempt); // 1
});
// ...
};
Sending Data
Data can be passed in several ways. One option is to use setData
method on the Emitter
.
const { emit } = useEmitter(emitMessage.setData({ message: "New message" }));
However, you may need to pass data dynamically, which requires using the emit
function.
const { emit } = useEmitter(emitMessage);
const handleSubmit = (message: string) => {
// ResponseDataType is automatically inherited from Emitter class
emit({ data: { message } }, (error: Error, data: ResponseDataType) => {
if (error) {
alert("No server response!");
} else {
alert("Message received on server.");
}
});
};
Options
Customize the behavior of useEmitter
by passing an options object as the second argument.
const { ... } = useEmitter(emitter, options)
Name | Type | Description |
---|---|---|
dependencyTracking |
|
Returns
useEmitter
returns an object containing the socket's state and helper methods.
const values = useEmitter(emitter);
Name | Type | Description |
---|---|---|
connected |
| |
connecting |
| |
emit |
| |
onConnected |
| |
onConnecting |
| |
onDisconnected |
| |
onEmit |
| |
onEmitError |
| |
onError |
| |
onReconnecting |
| |
onReconnectingFailed |
| |
setConnected |
| |
setConnecting |
| |
setData |
| |
setExtra |
| |
setTimestamp |
|