CSFrequency / react-firebase-hooks

React Hooks for Firebase.
Apache License 2.0
3.55k stars 304 forks source link

useCollection() - How to add an orderBy clause? #226

Closed aaronbentley closed 2 years ago

aaronbentley commented 2 years ago

Hello everyone 👋

Unfortunately I'm super tired today, and have that sinking feeling I've missed something trivial. I'm trying to add an orderBy clause to the useCollection hook, the following works without an orderBy clause:

const firestore = getFirestore(firebaseApp)

const Component = () => {

  const [values, loading, error] = useCollection(
    collection(firestore, 'feedbackCollection'),
    { snapshotListenOptions: { includeMetadataChanges: true } }
  )

  return (
    <Fragment>
      {values.docs.map((doc) => (
        <Fragment key={doc.id}>
          <Text color='white'>{doc.data()['feedback']}</Text>
          <Text color='white'>{doc.data()['name']}</Text>
         </Fragment>
      ))}
    </Fragment>
  )
}

However, if I add an orderBy clause (using the field 'timestamp') to the collection like so:

const [values, loading, error] = useCollection(
  collection(firestore, 'feedbackCollection').orderBy('timestamp', 'desc'),
  { snapshotListenOptions: { includeMetadataChanges: true } }
)

... I get the following console error:

Uncaught TypeError: (0 , firebase_firestore__WEBPACK_IMPORTED_MODULE_0__.collection)(...).orderBy is not a function

Where am I going wrong here? Is my primary issue a lack of sleep? 🥱

Thanks for taking the time to look at my issue.

renbesson commented 2 years ago

You probably figured it out by now but I'm gonna answer it just to leave registered.

You should wrap the collection function inside the query function alongside the orderBy function.

const [ingrs, ingLoading, ingError] = useCollectionData(
  query(collection(firestore, `users/${user?.uid}/ingredients/`), orderBy('id', 'desc'))
)

Of course, both orderBy and query should be imported as modules like collection is.

import { collection, orderBy, query } from 'firebase/firestore'

aaronbentley commented 2 years ago

Thank you @renbesson 🙌

Appreciate you taking the time to help me out here - have a great day my friend 🥳