crimx / observable-hooks

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

Unexpected error when using `useSubscription` for a `Subject` #122

Closed darkyzhou closed 1 year ago

darkyzhou commented 1 year ago

Minimal codes to reproduce:

export default function App() {
  const { current: someValue$ } = useRef(new Subject<number>());

  useSubscription(someObservable$, someValue$);

  // ...
}

Error:

截屏2023-08-15 11 28 53

Stackblitz URL: https://stackblitz.com/edit/stackblitz-starters-uzyyi8?devToolsHeight=33&file=src%2FApp.tsx

Suspicious cause in use-subscription-internal.ts:

const nextObserver =
  (argsRef.current[1] as PartialObserver<TInput>)?.next ||
  (argsRef.current[1] as ((value: TInput) => void) | null | undefined)
if (nextObserver) {
  // BUG: When argsRef.current[1].next presents, this way of calling the function
  // causes `this` to be missing which Subject's `next` relies heavily on.
  return nextObserver(value)
}

A possible fix, would love to open a PR for this:

const observer = argsRef.current[1];
if (observer && 'next' in observer && typeof observer.next === 'function') {
  return observer.next(value);
}

if (observer) {
  return observer(value);
}
crimx commented 1 year ago

observable-hooks@4.2.3 published.