Last active
August 3, 2020 06:06
-
-
Save jakejrichards/54b1588806d21f7d14439019e473ccdb 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 { 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