Repository navigation
hook sendevent
useSendEvent is a custom React hook that provides a unified interface for sending and subscribing to global events within your application. It is built on top of a generic event handler system, allowing you to trigger notifications, alerts, or any cross-cutting event from both React and non-React environments. This hook is ideal for decoupling event producers and consumers, such as triggering notifications from service workers, background scripts, or anywhere in your app.
import useSendEvent from '@/hooks/useSendEvent';
function MyComponent() {
const { sendEvent, subscribe, unsubscribe } = useSendEvent();
useEffect(() => {
const onInfo = (event) => {
// Handle info event (e.g., show notification)
console.log(event.title, event.description);
};
const unsubscribeInfo = subscribe('info', onInfo);
return () => unsubscribeInfo();
}, [subscribe]);
const handleClick = () => {
sendEvent({
eventType: 'info',
title: 'Hello!',
description: 'This is a global info event.',
});
};
return <button onClick={handleClick}>Send Info Event</button>;
}-
sendEvent(detail: GlobalEvent): void- Sends a global event. All listeners for the event type will be notified.
-
detailshould include at leasteventType,title, anddescription.
-
subscribe(eventType: EventType, listener: EventListener): () => void- Subscribes a listener to a specific event type (e.g.,
'info','error'). - Returns an unsubscribe function.
- Subscribes a listener to a specific event type (e.g.,
-
unsubscribe(eventType: EventType, listener: EventListener): void- Unsubscribes a listener from a specific event type.
-
'info'— Informational events -
'success'— Success events -
'warning'— Warning events -
'error'— Error events
You can also send events from outside React (e.g., service worker registration) using the exported sendEvent utility:
import { sendEvent } from '@/hooks/useSendEvent/eventHandler';
sendEvent({
eventType: 'success',
title: 'Update Available',
description: 'A new version is ready to use!'
});-
GlobalEvent:{ eventType: EventType; title: string; description: string; timeout?: number; } -
EventType:'info' | 'success' | 'warning' | 'error' -
EventListener:(event: GlobalEvent) => void
- To trigger notifications or global events from anywhere in your app, including non-React code.
- To decouple event producers (like service workers) from consumers (like notification UIs).
- For a scalable, maintainable event-driven architecture.
See also: useOfflineMode, NotificationProvider
This wiki documents NR Waste Plus for users and developers. Verify security and deployment guidance against the current application configuration before applying it elsewhere.
- Report an issue or ask a question in the GitHub repository.
- Follow the Contributing Guidelines to propose an update.
- Read the Code of Conduct.
Collection indexes support human browsing and machine retrieval. Keep both current when adding or moving wiki pages.
NR Waste Plus Wiki | GitHub Repository