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 58 59 60 61 62 63 64 65 66 67 | 4x 15x | import {
type Config,
type ReadableLike,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type Readable,
} from "@embra/reactivity";
import { useDerive } from "./useDerive";
import { useValue } from "./useValue";
export interface UseDerived {
/**
* Derive a new {@link Readable} with transformed value from the given {@link ReadableLike}.
* @param dep - The {@link ReadableLike} to derive from.
* @param transform - A pure function that takes an input value and returns a new value.
* @param config - Optional custom {@link Config}.
* @returns Transformed value from the given {@link ReadableLike}.
*/
<TDepValue, TValue>(
dep: ReadableLike<TDepValue>,
transform: (depValue: TDepValue) => TValue,
config?: Config<TValue>,
): TValue;
/**
* Derive a new {@link Readable} with transformed value from the given {@link ReadableLike}.
* @param dep - The {@link ReadableLike} to derive from, or a non-Readable value that will be returned as-is.
* @param transform A pure function that takes an input value and returns a new value.
* @param config - Optional custom {@link Config}.
* @returns Transformed value from the given {@link ReadableLike}, or `dep` itself if `dep` is not a {@link ReadableLike}.
*/
<TDepValue, TValue, U>(
dep: ReadableLike<TDepValue> | U,
transform: (depValue: TDepValue) => TValue,
config?: Config<TValue>,
): TValue | U;
}
/**
* Derive a new {@link Readable} from the given {@link ReadableLike}.
*
* Note that changes to `transform` and `config` will not trigger re-derivation, and `useDerive` always uses the latest `transform` and `config` in the derivation.
*
* @category Hooks
* @param dep - The {@link ReadableLike} to derive from, or a non-Readable value that will be returned as-is.
* @param transform Optional pure function that takes an input value and returns a new value.
* @param config - Optional custom {@link Config}.
* @returns Transformed value from the given {@link ReadableLike}, or `dep` itself if `dep` is not a {@link ReadableLike}.
*
* @example
* ```tsx
* import { useDerived } from "@embra/reactivity/react";
*
* function App({ position3d$ }) {
* const position2d = useDerived(
* position3d$,
* ({ x, y }) => ({ x, y }),
* { equal: (p1, p2) => p1.x === p2.x && p1.y === p2.y }
* );
* }
* ```
*/
export const useDerived: UseDerived = <TDepValue, TValue, U>(
dep: ReadableLike<TDepValue> | U,
transform?: (depValue: TDepValue) => TValue,
config?: Config<TValue>,
): TValue | U => useValue(useDerive(dep, transform!, config));
|