Firebase & Javascript – Sorting Data Using Firestore Queries Conditionally Through Dropdown Menu

While creating a project got stuck at a point. I want to sort the data according to the particular item selected from dropdown menu. I want to replace the first argument of onSnapshot function (colRef) with query variables conditionally.

The code relevant to the problem :-

data :

books(collection)
  document-1(doc)
    {
      "title": "title-1",
      "rating": 4.0,
      "year" : xxxx,
      "createdAt": created time
    }
  document-2(doc)
    {
       ....
       ....
    }

index.html :

<div class="sort-dropdown">
    <button>Alphabetical Order</button>
    <button>Rating</button>
    <button>Date</button>
    <button>Recent Book</button>
</div>

db.js :

// Initialize services
const db = getFirestore()

// collection reference
const colRef = collection(db, 'books')

// query references
const q1 = query(colRef, orderBy('title'))
const q2 = query(colRef, orderBy('rating'))
const q3 = query(colRef, orderBy('date'))
const q4 = query(colRef, orderBy('createdAt'))

// Getting realtime collection data
onSnapshot(colRef, (snapshot) => {
  snapshot.docChanges().forEach(change => {
    if(change.type === 'added'){
      renderList(change.doc.data(), change.doc.id);
    }
  })
})

const renderList = (data, id) => { ... using some dom elements to display data }