CSFrequency / react-firebase-hooks

React Hooks for Firebase.
Apache License 2.0
3.58k stars 305 forks source link

Using useCollection on a collection with the users ID #211

Closed 3DJakob closed 2 years ago

3DJakob commented 2 years ago

Hey, great component very useful! I cannot find a nice way to add your hook on a collection identified with the user's ID, however. The problem is that the user's ID is not known until after the first render. How would you write that code?

Example hook

const [firebaseCartItems, loading, error] = useCollection(collection(getFirestore(app), 'users', auth.currentUser?.uid, 'cart'))

One solution could be wrapping your whole app in a component that waits for the auth.currentUser.uid and then renders the app and passes the id I guess.

DanielBailey-web commented 2 years ago

Although undefined does not work as a value for useCollection; null does. So you can use a tertiary as the input of your hook. I would recommend memoizing this value so that you do not have to worry about any extra renders at a very high level of your app.

const uid = auth.currentUser?.uid
const usersCart = useMemo(()=> uid ?  collection(getFirestore(app), 'users', uid, 'cart') : null, [uid])
const [firebaseCartItems, loading, error] = useCollection(usersCart);

Also, if you are initializing your app, you need to pass app to getFirestore.

3DJakob commented 2 years ago

Thank you I'll do it like that 👍