All files / src/react useCombined.ts

100% Statements 7/7
100% Branches 1/1
100% Functions 1/1
100% Lines 7/7

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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                1x 1x                                                                                   1x 16x 16x 16x 16x  
import {
  type Config,
  type MapReadablesToValues,
  type ReadableLike,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  type Readable,
} from "@embra/reactivity";
 
import { useCombine } from "./useCombine";
import { useValue } from "./useValue";
 
export interface UseCombined {
  /**
   * Combines an array of {@link ReadableLike}s into an array of values.
   * @param deps An array of {@link ReadableLike}s to combine.
   * @returns The combined values.
   */
  <TDeps extends readonly ReadableLike[]>(deps: TDeps): MapReadablesToValues<TDeps>;
  /**
   * Combines an array of {@link ReadableLike}s into a transformed value.
   * @param deps An array of {@link ReadableLike}s to combine.
   * @param transform A pure function that takes an array of values and returns a new value.
   * @param config custom config for the combined Readable.
   * @returns The transformed values.
   */
  <TDeps extends readonly ReadableLike[], TValue>(
    deps: TDeps,
    transform: (deps: MapReadablesToValues<TDeps>) => TValue,
    config?: Config<TValue>,
  ): TValue;
}
 
/**
 * Combines an array of {@link ReadableLike}s into a transformed value.
 *
 * Note that changes to `transform` and `config` will not trigger re-derivation, and `useCombine` always uses the latest `transform` and `config` in the derivation.
 * In other words, no extra care is needed to use this in React components. All args will be updated properly.
 *
 * @example
 * ```tsx
 * import { useCombined } from "@embra/reactivity/react";
 *
 * function App({ width$, height$ }) {
 *   const size = useCombined(
 *     [width$, height$],
 *     ([width, height]) => ({ width, height }),
 *     { equal: (s1, 22) => s1.width === s2.width && s1.height === s2.height }
 *   );
 * }
 * ```
 */
export const useCombined: UseCombined = <TDeps extends readonly ReadableLike[], TValue>(
  deps: TDeps,
  transform?: (deps: MapReadablesToValues<TDeps>) => TValue,
  config?: Config<TValue>,
): TValue => useValue(useCombine(deps, transform!, config));