1.0.0 • Published 11 months ago

@kambing86/event-bus-ts v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
11 months ago
npm install --save-dev @kambing86/event-bus-ts

1) add @kambing86/event-bus-ts by installing npm install @kambing86/event-bus-ts 2) create a file for event bus, for eg. "src/util/eventBus.ts"

import { createEventBus, createUseEventBus } from '@kambing86/event-bus-ts';

// string enum for Event
export enum EventType {
  ADD_TODO = 'addTodo',
  REMOVE_TODO = 'removeTodo',
}

// or just const
export const EventType = {
  ADD_TODO: 'addTodo',
  REMOVE_TODO: 'removeTodo',
} as const;

// define the payload data for Event
export type EventDataMapping = {
  [EventType.ADD_TODO]: { id: number; text: string };
  [EventType.REMOVE_TODO]: number;
};

export const eventBus = createEventBus<EventDataMapping>();

export const useEventBus = createUseEventBus<EventDataMapping>(eventBus);

3) then use it in React component

function NewTodo() {
  // ...
  return <button onClick={() => eventBus.dispatch(EventType.ADD_TODO, newTodo)}>Add new</button>
}

function TodoList() {
  const [todoList, setTodoList] = useState([]);

  // ...

  useEventBus(EventType.ADD_TODO, (newTodo) =>
    setTodoList((prev) => [...prev, newTodo]),
  );

  return <div>{todoList.map((todo) => <div>{todo.text}</div>)}</div>
}
1.0.0

11 months ago

0.0.1

1 year ago