Last active
January 20, 2019 04:37
-
-
Save anaisbetts/b73f26574e4739fe07eb260c17e1c227 to your computer and use it in GitHub Desktop.
always use function parameters
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
function Example() { | |
// Crap, we just made a Firebase query for each render instead of | |
// what we wanted, a query set up on mount, and cleaned up on unmount | |
const query = useQuery(db.collections('lots-of-stuff').limit(10000)); | |
return <ul>query.docs.map(x => (<li>{x}</li>)); | |
} |
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
export function useQuery(query: /*Firebase */Query) { | |
return useObservable<QuerySnapshot>(() => | |
concat( | |
query.get(), | |
queryUpdates(q).pipe(filter(x => x && x.docChanges().length > 0)) | |
) | |
); | |
} | |
export function useQueryMoreBetter(query: () => Query) { | |
const [q] = useState(query); | |
return useObservable<QuerySnapshot>(() => | |
concat( | |
q.get(), | |
queryUpdates(q).pipe(filter(x => x && x.docChanges().length > 0)) | |
) | |
); | |
} | |
export function useObservable<T>( | |
target: () => Observable<T>, | |
initial?: T | |
): T | undefined { | |
const [ret, setter] = useState(initial); | |
const [obs] = useState(target()); | |
useEffect( | |
() => { | |
const sub = obs.subscribe(setter); | |
return sub.unsubscribe.bind(sub); | |
}, | |
[obs] | |
); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment