crimx / observable-hooks

⚛️☯️💪 React hooks for RxJS Observables. Concurrent mode safe.
https://observable-hooks.js.org
MIT License
1.03k stars 44 forks source link

useObservableState(BehaviorSubject) gives undefined when first rendering #88

Closed NoMoreViolence closed 3 years ago

NoMoreViolence commented 3 years ago

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)

Paitum commented 3 years ago

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 3 years ago

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