Typesafe Event Emitter examples:
Installation:
npm i event-emitter-typescript 📑
TypeScript
import {EventEmitter} from "event-emitter-typescript";
const eventEmitter = new EventEmitter<{
userRegistered: { name: string; email: string; };
otherEvent: { data: string; };
}>();
// typesafe, we have inferred user type here
const unsubscribe = eventEmitter.on("userRegistered", async (user) => {
await userRepository.save(user);
});
// typesafe
eventEmitter.emit("userRegistered", { name: "John Doe", email: "johndoe@example.org" });
// typescript error, email should be present
eventEmitter.emit("userRegistered", { name: "John Doe" });
// Usage in react components:
function App() {
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribeFn = eventEmitter.on('userRegistered', (user) => {
setUser(user)
});
return () => {
unsubscribeFn();
};
}, []);
if (!user) {
return 'loading';
}
return <div>{user?.name}</div>
}
// Or with a custom hook:
export const useEvent = <E extends keyof ActualEventMap>(
event: E,
handler: (data: ActualEventMap[E]) => void,
deps: unknown[] = [],
) => {
useEffect(() => {
const unsubscribe = eventEmitter.on(event, handler);
return () => {
unsubscribe();
};
}, [event, ...deps]);
};
function App() {
const [user, setUser] = useState(null);
useEvent('userRegistered', (user) => {
setUser(user);
}, [setUser]);
if (!user) {
return 'loading';
}
return <div>{user?.name}</div>
}