Last active
August 9, 2024 17:23
-
-
Save yoSteve/9020c17f668d7e4f5c5a21f8ca3009a9 to your computer and use it in GitHub Desktop.
React Hooks for interacting with RxJS Observables and managing subscriptions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 will return the error if that event 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 | null, unknown ] { | |
const [ value, setValue ] = useState<T | null>(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