Event emitter to manage your state.
An event emitter that allows you to manage your global state. Instead of using global giant object to store your shared sate, you can simply emit the events you need with the necessary payload and keep your state managed locally.
npm install thor-event
Somewhere in your code:
import ThorEvent from "thor-event";
const appEvent = new ThorEvent();
appEvent.emit({
id: "evt-1",
type: "auth",
issuer: "api.auth.com",
type: "auth", // notify all listeners of this type
payload: {
name: "name",
address: "address-1",
},
});
And inside you React JSX component
const handleUserAuth = ({payload, ...rest}: UserInfo) => {
// update my state locally
setUserInfo({...payload)};
// do something else with the rest
};
React.useEffect(() => {
appEvent.on("auth", handleUserAuth);
return () => {
appEvent.off("auth", handleUserAuth);
};
}, []);
return (
<div>
<p>userInfo</p>
</div>
);
Initialize the event emitter (optional):
init(evt: EventInterface<EventTypes, PayLoadInterface, IssuerTypes>)
The evt object contains:
id?: string
,type?: EventTypes | string
,issuer?: IssuerTypes | string
,payload?: PayLoadInterface | any
,
Update the payload of an event:
setPayload(evt: EventInterface<EventTypes, PayLoadInterface, IssuerTypes>)
Update the id of an event:
updateID({ id, newID });
id: string
,newID: string
,
To get all events from the same type:
getEventsByType(type?: EventTypes | string) : EventInterface[]
Bind an event listener to an event type:
on(type: EventTypes | string, listeners: (evt: EventInterface<EventTypes, PayLoadInterface, IssuerTypes>) => void)
Emit an event:
emit(evt: EventInterface<EventTypes, PayLoadInterface, IssuerTypes>)
To clear event and its binding listeners:
clear(id:string)
Unbind an event listener:
off(type: EventTypes | string, listeners: (evt: EventInterface<EventTypes, PayLoadInterface, IssuerTypes>) => void)
npm test
This project is licensed under the MIT