-
-
Save designdevy/cc05f1ceb01b51848328367a029ca9f8 to your computer and use it in GitHub Desktop.
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 _ from "lodash"; | |
import { map, filter } from "lodash/fp"; | |
import { useEffect } from "react"; | |
import { Query } from "@google-cloud/firestore"; | |
interface Entity { | |
id: string; | |
} | |
interface FirebaseHookHandlers { | |
subscribe: () => void; | |
error: (error: Error) => void; | |
unsubscribe: () => void; | |
} | |
interface CollectionHandlers<T extends Entity> extends FirebaseHookHandlers { | |
data: (data: T[]) => void; | |
} | |
export const useCollection = <T extends Entity>( | |
query: () => Query, | |
handlers: CollectionHandlers<T>, | |
deps: any[] | |
) => { | |
useEffect(() => { | |
handlers.subscribe(); | |
const unsubscribeFromQuery = query().onSnapshot( | |
snapshot => { | |
const docs = _.flow( | |
() => snapshot.docs, | |
map(dataFromSnapshot), | |
filter<T>(d => !!d) | |
)(); | |
handlers.data(docs); | |
}, | |
error => { | |
handlers.error(error); | |
} | |
); | |
return () => { | |
handlers.unsubscribe(); | |
unsubscribeFromQuery(); | |
}; | |
}, deps); // eslint-disable-line react-hooks/exhaustive-deps | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment