Use the event bus
Squide provides a built-in event bus so that modules and other parts of a modular application can communicate in a loosely coupled way.
For more details, refer to the useEventBusListener and useEventBusDispatcher reference documentation.
Add an event listener
Register a function that will be invoked each time the specified event is dispatched:
import { useCallback } from "react";
import { useEventBusListener } from "@squide/firefly";
const handleShowToast = useCallback(data => {
// Do something...
}, []);
// Listen to every "show-toast" events.
useEventBusListener("show-toast", handleShowToast);
Add an event listener that will be invoked once
Register a function that will be invoked once, and then automatically unregisters itself:
import { useCallback } from "react";
import { useEventBusListener } from "@squide/firefly";
const handleShowToast = useCallback(data => {
// Do something...
}, []);
// Listen to the first "show-toast" event.
useEventBusListener("show-toast", handleShowToast, { once: true });
Dispatch an event
import { useEventBusDispatcher } from "@squide/firefly";
const dispatch = useEventBusDispatcher();
// Dispatch a "show-toast" event with a string payload.
dispatch("show-toast", "Hello!");
Setup the typings
Before dispatching or listening to events, modules should augment the EventMap interface with the events they intend to use to ensure type safety and autocompletion.
First, create a types folder in the project:
project
├── src
├────── register.tsx
├────── Page.tsx
├────── index.tsx
├────── App.tsx
├── types
├────── event-map.d.ts
Then create an event-map.d.ts file:
import "@squide/firefly";
declare module "@squide/firefly" {
interface EventMap {
// Each entry maps an event name to its payload type.
"show-toast": string;
}
}
Finally, update the project tsconfig.json to include the types folder:
{
"compilerOptions": {
"incremental": true,
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json",
"types": [
"./types/event-map.d.ts"
]
},
"exclude": ["dist", "node_modules"]
}
If any other project using those events must also reference the project's event-map.d.ts file:
{
"compilerOptions": {
"incremental": true,
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json",
"types": [
"../another-project/types/event-map.d.ts"
]
},
"exclude": ["dist", "node_modules"]
}
Once configured, the event bus hooks are fully typed: