Last active
February 21, 2022 21:19
-
-
Save erictherobot/3dd624a2749bdc65bfc31dcac739f0ec to your computer and use it in GitHub Desktop.
Firebase / Firestore version 9 SDK useDocument React Hook
This file contains hidden or 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, useState } from 'react'; | |
import { doc, getDoc, DocumentData } from 'firebase/firestore'; | |
import { db } from '@/lib/firebase'; | |
export function useDocument(collection: string, id: string, callback?: any) { | |
const [data, setData] = useState<DocumentData | undefined>(undefined); | |
const [loading, setLoading] = useState<boolean>(false); | |
const [error, setError] = useState<any>(null); | |
useEffect(() => { | |
const getDocument = async () => { | |
setLoading(true); | |
try { | |
const docRef = doc(db, collection, id); | |
const docSnap = await getDoc(docRef); | |
if (docSnap.exists()) { | |
setData(docSnap.data()); | |
} else { | |
setData(undefined); | |
console.log('No document!'); | |
} | |
} catch (e) { | |
setError(e.message); | |
} | |
setLoading(false); | |
}; | |
getDocument(); | |
}, [callback]); | |
return { data, loading, error }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment