Created
May 6, 2019 21:26
-
-
Save jemmyw/04e3579f5c2b510d240face59848c4da to your computer and use it in GitHub Desktop.
useSubscription
This file contains 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, Subscription } from 'rxjs'; | |
export const useSubscription = (fn: () => Subscription, inputs: any[]) => { | |
return useEffect(() => { | |
const subscription = fn(); | |
return () => subscription.unsubscribe(); | |
}, inputs); | |
}; | |
export const useSubscriptionState = <T>( | |
fn: () => Observable<T>, | |
inputs: any[] | |
): [T | null, boolean] => { | |
const [state, setState] = useState<T | null>(null); | |
const [loading, setLoading] = useState(true); | |
useSubscription( | |
() => | |
fn().subscribe(n => { | |
setState(n); | |
setLoading(false); | |
}), | |
inputs | |
); | |
return [state, loading]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment