Skip to content

Instantly share code, notes, and snippets.

@jakejrichards
Last active August 3, 2020 06:06
Show Gist options
  • Save jakejrichards/54b1588806d21f7d14439019e473ccdb to your computer and use it in GitHub Desktop.
Save jakejrichards/54b1588806d21f7d14439019e473ccdb to your computer and use it in GitHub Desktop.
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
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment