1

I have a page which shows some collections from my firestore database, I am struggling to work out how to use the orderBy function to show the documents in a specific order.

I'm not sure where to put orderBy in the code. I would like to order them by a field from the firestore documents called 'section'.

I've been trying this week following other tutorials and answers from StackOverflow but can't yet work it out.

import React, { useEffect, useState, Component, setState }  from 'react';
import { collection, getDocs, getDoc, doc, orderBy, query } from 'firebase/firestore';
import "./AllSections.css";
import { Firestoredb } from "../../../../../firebase.js";
import AllCourses from './AllCourses';
import ReactPlayer from 'react-player'

import ViewSection from './ViewSection';
import SectionsTabData from './SectionsTabData';
import {
  BrowserRouter as Router,
  Link,
  Route,
  Routes,
  useParams,
} from "react-router-dom";
import VideoJS from './VideoJS';



function SectionsData() {


  const videoJsOptions = {
    controls: true,
    sources: [{
      src: sectionVideo,
      type: 'video/mp4'
    }]
  }

  const {courseId} = useParams();

  const {collectionId} = useParams();

  const params = useParams();

  const [sectionId, setSectionId] = useState('');

  const [sectionImage, setSectionImage] = useState('');

  const [sectionVideo, setSectionVideo] = useState('');
  
  const [sectionContent, setSectionContent] = useState('');


    const [isShown, setIsShown] = useState(false);
    const handleClick = event => {
        // ️ toggle shown state
        setIsShown(current => !current);
    }
    

    const [active, setActive] = useState();


    const [id, setID] = useState("");


    const [Sections, setCourses, error, setError] = useState([]);

    useEffect(() => {
      getSections()
    }, [])
  
    useEffect(() =>{
      console.log(Sections)
    }, [Sections]) 
  
    function getSections() {
        const sectionsCollectionRef = collection(Firestoredb, collectionId, courseId, 'Sections'); 
        orderBy('section')
        getDocs(sectionsCollectionRef)
        .then(response => {
          const content = response.docs.map(doc => ({
            data: doc.data(), 
            id: doc.id,
          }))
          setCourses(content)
        })
        .catch(error => console.log(error.messaage))
        

        
      }

        const handleCheck = (id, image, video, content) => {
        console.log(`key: ${id}`)
        /*alert(image)*/
        setSectionId(id)
        setSectionImage(image)
        setSectionVideo(video)
        setSectionContent(content)
      }
      
  
    return (
        
      <>
      <div className='MainSections'> 

        <div className='Sidebar2'>
              
              <ul className='SectionContainer'
               >
                {Sections.map(section => <li className='OneSection' key={section.id} 
                
                style={{
                    width: isShown ? '100%' : '200px',
                    height: isShown ? '100%' : '50px',
                }}
                onClick={() => 
                  handleCheck(section.id, section.data.thumbnailImageURLString, section.data.videoURLString, section.data.contentURLString)}

                id = {section.id}
                >
               
                <br />
                {section.data.name}
                  <br />
                  <br />
                  {isShown && (
                  <img className='SectionImage' src={section.data.thumbnailImageURLString !== "" ? (section.data.thumbnailImageURLString) : null} alt='section image'></img>
                  )}
                  <br />
                  </li>)}
              </ul>
              </div>
              <div className='ViewSection'>
                
                <iframe className='Content' src={sectionContent} 
                 width="100%"/>
              </div>
          </div>
          
          </>
    
    )

    
}

export default SectionsData
  • why does your collection query have a ; at the end instead of chaining (.) queryBy()? it should be collection(Firestoredb, collectionId, courseId, 'Sections').orderBy('section') – sid Aug 17 '22 at 15:30

2 Answers2

1

You are using orderBy incorrectly please view the docs here: https://firebase.google.com/docs/firestore/query-data/order-limit-data

Your query should look something along these lines if you're trying to order your data in a specific way. Assuming your sectionsCollectionRef is correct:

  const sectionsCollectionRef = collection(Firestoredb, collectionId, courseId, 'Sections')
  const q = query(sectionsCollectionRef, orderBy('section', 'desc'))
  const querySnapshot = await getDocs(q);
Rob Terrell
  • 2,398
  • 1
  • 14
  • 36
  • I see, this is helpful. I'm still not able to get it to work however? When I add the querySnapshot const it comes up with the following error: Parsing error: Unexpected reserved word 'await'. – Peter Bonnebaigt Aug 18 '22 at 05:55
  • await is used in asynchronous functions...you would need to convert your getSections function to be async. I had assumed you had some understanding of async functions prior to providing you with this answer. – Rob Terrell Aug 18 '22 at 16:09
0

The orderBy() won't do anything on it's own. You must use it along query() function to add the required QueryConstraint and build a Query as shown below:

import { collection, query } from "firebase/firestore"

const sectionsCollectionRef = collection(Firestoredb, collectionId, courseId, 'Sections'); 

const sectionsQueryRef = query(sectionsCollectionRef, orderBy("section"))
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • Also checkout [this answer](https://stackoverflow.com/q/69036031/13130697) and the [documentation](https://firebase.google.com/docs/firestore/query-data/order-limit-data#web-version-9) to learn more about building queries. – Dharmaraj Aug 17 '22 at 15:37
  • Will this line work on its own or do I need to use sectionsQueryRef somewhere else in the code to make it work? – Peter Bonnebaigt Aug 18 '22 at 06:07
  • In fact, it is working now! Thank you! I realise now that I needed to pass sectionQueryRef into getDocs – Peter Bonnebaigt Aug 18 '22 at 06:10