Skip to content

Instantly share code, notes, and snippets.

@yoSteve
Created September 7, 2023 19:35
Show Gist options
  • Save yoSteve/9020c17f668d7e4f5c5a21f8ca3009a9 to your computer and use it in GitHub Desktop.
Save yoSteve/9020c17f668d7e4f5c5a21f8ca3009a9 to your computer and use it in GitHub Desktop.
React Hooks for interacting with RxJS Observables and managing subscriptions.
import { useEffect, useState } from 'react';
import { Observable } from 'rxjs';
/**
* A React hook that manages the subscription of a source Observable, and calls event handlers
* when source emits 'next' and 'error' events.
*
* @param source$ an Observable of type T
* @param nextHandler a function to be called when source$ emits next value
* @param errorHandler a function to be called if source$ emits error
*/
export function useSubscription<T>(
source$: Observable<T>,
nextHandler: (value: T) => void,
errorHandler?: (err: unknown) => void
) {
useEffect(() => {
if (source$) {
const subscription = source$.subscribe({
next: nextHandler,
error: e => {
errorHandler && errorHandler(e);
console.log(e);
}
});
return () => subscription.unsubscribe();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ source$ ]);
}
/**
* A React hook that receives a source Oobservable, and an initial value.
* It uses 'useSubscription' under the hood to manage subsription.
* It returns the value whenever the Observable emits, and the error should that event occur.
*
* @param source$ an Observable of type T
* @param initialValue an initial value of type T. Default is null.
* @returns [ value: T, error?: uknown ]
*/
export function useObservable<T>(source$: Observable<T>, initialValue?: T): [ T, unknown ] {
const [ value, setValue ] = useState<T>(initialValue as T || null);
const [ error, setError ] = useState<unknown>();
useSubscription(source$, setValue, setError);
return [ value, error ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment