use-observable-hooks
    Preparing search index...

    Function useBehaviorSubject

    Implementation of useBehaviorSubject.

    • Hook to use an RxJS BehaviorSubject.

      Returns the current value, a function to emit a new value, and any error. A BehaviorSubject always has a current value and emits it to new subscribers.

      Type Parameters

      • SubjectValue

        The type of the value emitted by the subject.

      • SubjectError = unknown

        The type of the error that can be emitted by the subject. Defaults to unknown.

      Parameters

      • initialValue: SubjectValue

        The initial value for the BehaviorSubject.

      Returns [SubjectValue, (value: SubjectValue) => void, SubjectError | undefined]

      A tuple containing:

      • The current value of the BehaviorSubject.
      • A function to emit a new value to the subject.
      • The error emitted by the subject (if any).
      import { useBehaviorSubject } from 'use-observable-hooks';

      function Counter() {
      const [count, setCount] = useBehaviorSubject(0);

      return (
      <button onClick={() => setCount(count + 1)}>
      Count: {count}
      </button>
      );
      }
    • Hook to use an RxJS BehaviorSubject with pipe operations.

      Type Parameters

      • SubjectValue

        The type of the value emitted by the subject after piping.

      • SubjectError = unknown

        The type of the error that can be emitted by the subject. Defaults to unknown.

      Parameters

      • initialValue: any

        The initial value for the BehaviorSubject.

      • ...operations: OperatorFunction<any, any>[]

        Operator functions to pipe to the subject.

      Returns [SubjectValue, (value: any) => void, SubjectError | undefined]

      A tuple containing:

      • The current value of the BehaviorSubject (after piping).
      • A function to emit a new value to the subject.
      • The error emitted by the subject (if any).
      import { useBehaviorSubject } from 'use-observable-hooks';
      import { map } from 'rxjs/operators';

      function DoubleCounter() {
      const [doubledCount, setCount] = useBehaviorSubject(
      0,
      map((n) => n * 2)
      );

      return (
      <button onClick={() => setCount(doubledCount / 2 + 1)}>
      Doubled Count: {doubledCount}
      </button>
      );
      }