Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useEffect } from "react";
- import { DocumentReference } from "@google-cloud/firestore";
- interface Entity {
- id: string;
- }
- interface FirebaseHookHandlers {
- subscribe: () => void;
- error: (error: Error) => void;
- unsubscribe: () => void;
- }
- interface DocHandlers<T extends Entity> extends FirebaseHookHandlers {
- data: (data: T | undefined) => void;
- }
- export const useDoc = <T extends Entity>(
- getDocReference: () => DocumentReference,
- handlers: DocHandlers<T>,
- deps?: any
- ) => {
- useEffect(() => {
- handlers.subscribe();
- const unsubscribeFromDoc = getDocReference().onSnapshot(
- snapshot => handlers.data(dataFromSnapshot(snapshot)),
- error => handlers.error(error)
- );
- return () => {
- handlers.unsubscribe();
- unsubscribeFromDoc();
- };
- }, deps); // eslint-disable-line react-hooks/exhaustive-deps
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement