import { useRegisterEventListener } from '@uhg-abyss/parcels/hooks/useRegisterEventListener';Overview
The useRegisterEventListener hook is used to register event listeners for custom events dispatched to the window, enabling communication between web/parcel components.
This hook is useful for listening to events dispatched by other components.
This hook is meant to be used in conjunction with the dispatchEvent tool.
useRegisterEventListener is built using React and uses a useEffect hook internally that automatically provides a cleanup mechanism ensuring
that the event listener is removed and preventing potential memory leaks. This differs from the
registerEventListener tool where this cleanup is not provided and will need to be added independently.
This hook is bidirectional, meaning that it can be used to register events in both web and parcel components.
Properties
useRegisterEventListener( eventName: string, handler: (event) => void,):Usage
useRegisterEventListener takes in two parameters:
eventName: a string representing the name of the custom event to listen for.handler: a callback function that is executed when the event is dispatched.
() => { const [text, setText] = useState('Hello');
useRegisterEventListener('webSubmit', (event) => { setText(event.detail.message); });
return <div>{text}</div>;};Example
// Example web fileimport React from 'react';import { Button } from '@uhg-abyss/web/ui/Button';import { dispatchEvent } from '@uhg-abyss/parcels/tools/dispatchEvent';
export const HelloAbyss = () => { // 1. Add a dispatch event to the web component const onSubmit = () => { // When the button is clicked, the event will be dispatched dispatchEvent('webSubmit', { message: 'Form submitted!' }); }; return ( <div> <abyss-parcel import="parcel-app@test" /> <Button onClick={onSubmit}>Hello</Button> </div> );};// Example parcel fileimport React, { useCallback, useState } from 'react';import { useRegisterEventListener } from '@uhg-abyss/parcels/hooks/useRegisterEventListener';
export const ParcelApp = () => { const [text, setText] = useState('Hello');
// Memoize the handler function using useCallback // By using useCallback, you prevent useRegisterEventListener from unnecessarily // removing and re-adding the event listener whenever the component re-renders const handleWebSubmit = useCallback((event) => { setText(event.detail.message); }, []); // Dependencies array is empty since setText doesn't change
// 2. Add a register event to the parcel component to listen for when the parcel component dispatches the event useRegisterEventListener('webSubmit', handleWebSubmit);
return <div>{text}</div>;};