Skip to content

Instantly share code, notes, and snippets.

@designdevy
Forked from jakejrichards/useCollection.ts
Created August 3, 2020 06:05
Show Gist options
  • Save designdevy/cc05f1ceb01b51848328367a029ca9f8 to your computer and use it in GitHub Desktop.
Save designdevy/cc05f1ceb01b51848328367a029ca9f8 to your computer and use it in GitHub Desktop.
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