crimx/observable-hooks

useObservableState(BehaviorSubject) gives undefined when first rendering

NoMoreViolence opened this issue · 2 comments

The title says it all

import { BehaviorSubject } from "rxjs";
import { useObservableState } from "observable-hooks";

const tempBehavior$ = new BehaviorSubject({ hello: "message" });

export default function App() {
  const tempBehavior = useObservableState(tempBehavior$);

  return <div>{tempBehavior.hello}</div>;
}

Test Link is here: https://codesandbox.io/s/aged-butterfly-rqzwb?file=/src/App.tsx

the typing about this form should be like that

export function useObservableState<TState>(
  input$: BehaviorSubject<TState>
): TState

rxjs version: 6, 7 (both not working)

If you want to have the initial value synchronously extracted from the BehaviorSubject then you should consider using useObservableEagerState https://observable-hooks.js.org/api/#useobservableeagerstate .

Alternatively, you could provide the useObservableState an "initial value" as its second argument. Like:

  const tempBehavior = useObservableState(tempBehavior$, {});
crimx commented

This is actually a bug. useObservableState should pick up the BehaviorSubject.value automatically. I am fixing the tests to reflect that.