11import { useCompareEffect } from '../shared' ;
2- import { useRef , useCallback , useContext } from 'react' ;
2+ import { useRef , useCallback } from 'react' ;
33import fastCompare from 'react-fast-compare' ;
44import { HttpEventClassType , HttpEventHandler } from './types' ;
5- import { EventBusContext } from './event-bus-context' ;
5+ import { useEventBus } from './event-bus-context' ;
66
77export const useBusSubscribe = < T > (
88 eventName : HttpEventClassType < T > ,
99 handler : HttpEventHandler < T >
1010) : void => {
1111 // The event bus.
12- const eventBus = useContext ( EventBusContext ) ;
12+ const eventBus = useEventBus ( ) ;
1313
1414 // A ref to unsubscribe from the event. It helps to avoid
1515 // registering the same event handler multiple times.
1616 const unsubscribeRef = useRef < ( ) => void > ( ) ;
1717
18+ // Keeps track of the first run of the hook and the related subscription.
19+ const firstRunRef = useRef ( true ) ;
20+ const unsubcribeFirstRunRef = useRef < ( ) => void > ( ) ;
21+
22+ // Subscribe to the event on first hook run. "useEffect" hook will first
23+ // run after component rendering, if child components cause http events to
24+ // be triggered they want be receveived from this subscriber.
25+ if ( firstRunRef . current ) {
26+ unsubcribeFirstRunRef . current = eventBus . subscribe ( eventName , handler ) ;
27+ firstRunRef . current = false ;
28+ }
29+
1830 /**
1931 * Detach the handler for the event.
2032 */
@@ -30,6 +42,10 @@ export const useBusSubscribe = <T>(
3042 */
3143 useCompareEffect (
3244 ( ) => {
45+ if ( unsubcribeFirstRunRef . current ) {
46+ unsubcribeFirstRunRef . current ( ) ;
47+ unsubcribeFirstRunRef . current = undefined ;
48+ }
3349 // Subscribe to the event and keep track of the subscription.
3450 unsubscribeRef . current = eventBus . subscribe ( eventName , handler ) ;
3551
0 commit comments