All files / src/useSubscription useSubscription.ts

100% Statements 10/10
100% Branches 0/0
100% Functions 8/8
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25              17x   8x 8x 6x 6x         25x     11x   17x    
import { useEffect, useRef } from "react";
 
import type { SubscriptionManager } from "./SubscriptionManager";
/**
 * This hook provides a simple subscription semantic to React components.
 */
export function useSubscription<T = unknown>(): SubscriptionManager<T> {
  const subscribersRef = useRef<((data: T) => void)[]>([]);
  function subscribe(fn: (data: T) => void) {
    subscribersRef.current.push(fn);
    return () => {
      subscribersRef.current = subscribersRef.current.filter(
        (subscription) => !Object.is(subscription, fn)
      );
    };
  }
  function notify(data: T) {
    subscribersRef.current.forEach((fn) => fn(data));
  }
  function useSubscribeEffect(fn: (data: T) => void) {
    useEffect(() => subscribe(fn), [fn]);
  }
  return { subscribe, notify, useSubscribeEffect };
}