Home > Enterprise >  Order Firebase data returned by collection name
Order Firebase data returned by collection name

Time:06-27

I'm sorry if this has been asked but I have found many questions about ordering by field contents. I would like to order by field names. I have tried orderBy, orderByChild and startAt - none of which worked.

My collection looks like this: Firebase

I would like my data to always start with 'All', after that the order does not matter. Here's how I fetch the data:

 const fetchProjects = async() => {
      const catRef = doc(db, 'Portfolio', 'Category')
      const catSnap = await getDoc(catRef)

      if(catSnap.exists()) {
          setCategory(catSnap.data())
      }
}

And then I create buttons to select certain fields of data as below:

       const sortButton = (key) => {
      if(filter === key) {
        return (<div key={key}>
          <button className='prt-act-btn' >{key}</button>
          </div>)
      } else {
        return ( <div key={key}>
            <button className='prt-btn' onClick={() => setFilter(`${key}`)}>{key}</button>
            </div> )}
    }
    
    if(loading || fetching) {
      return <p>loading...</p>
    }
    
      return (
        <>
           <p className="pageHeader"> <FaFileArchive/> &nbsp; Portfolio</p>
           <div className='center'>
           {Object.keys(category).map((key) => (
            sortButton(key) 
           ))}
           </div>
}

So essentially the problem is that my buttons are randomized in order after each reload and I would like to start with 'All' and then list the other categories like 'API', 'Blockchain', 'Database' etc.

Thank you for any help!

CodePudding user response:

Javascript objects are not meant for ordered data. Object do technically have an order to their keys, but you have little ability to control that order and should not rely on it. So when you do Object.keys(/* some object */), you should mentally treat it as though you're getting the keys in a random order. You happen to be getting this object from a firestore document, but the same thing would happen with any object.

If you want to put the keys into an order you can, but you'll need to add code to do so. The .sort function can help with this. For example, if you want to put 'All' first, and then the rest in alphabetical order you might do:

{Object.keys(category)
  .sort((a, b) => {
    if (a === 'All') {
      return -1;
    } else if (b === 'All') {
      return 1;
    } else {
      return a.localeCompare(b);
    }
  })
  .map(key => sortButton(key))
}
  • Related