crimx/observable-hooks

`useObservableEagerState`: incorrect return type

OliverJAsh opened this issue · 6 comments

The type definitions say that useObservableEagerState will always return TState but it's possible for it to also return undefined if the observable provided doesn't emit a value synchronously. Reduced test case: https://stackblitz.com/edit/react-ultydo?file=src%2FApp.js

What do you think about updating the return type to be TState | undefined?

It feels wrong to do that because useObservableEagerState is only intended to be used with observables that do emit a value synchronously—but there's no way for us to enforce that at the type level, as far as I know. (Maybe traits will help?)

crimx commented

It feels wrong to do that because useObservableEagerState is only intended to be used with observables that do emit a value synchronousl

You are right.

If the observable is possible to not emit value synchronously, then it is not safe to assume any synchronous state value. you should either provide the initial state or stick to useObservableState.

crimx commented

Maybe useObservableEagerState should giva a warning if no synchronous value is detected.

Or perhaps it could throw an error. Otherwise the types can't be trusted—TS will think you have TState but in fact you have TState | undefined. Better to fail loudly/quickly?

crimx commented

Or perhaps it could throw an error.

You are right.

Too bad that I can't think of a way to identify synchronous observable. useObservableEagerState is designed for specific use case. If the observable is arbitrary then it is not safe to use useObservableEagerState.

That's what the forthcoming traits are supposed to be useful for. https://www.youtube.com/watch?v=vC1KXMo97XI