Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Ordering data coming from FireBase

Tags:

hook

The following component connects to a FireBase collection, called FlashCards, gets the data using get() function and then save them inside the cards using the setCards.

import React, { useState, useEffect } from 'react';
import { db } from '../firebase';

const List = () => {
  const [cards, setCards] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const data = await db
        .collection('FlashCards')
        .get()
      setCards(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
    };
    fetchData();
  }, []);

  return (
    <>
      <ul>
        {cards.map((card) => (
          <li key={card.id}>
            {card.customId}
            {card.originalText}
          </li>
        ))}
      </ul>
    </>
  );
};

export default List;

Each document in the collection FlashCards has a field called customId. I want to order my data by that customId.

For this I tried the following:

useEffect(() => {
    const fetchData = async () => {
      const data = await db
        .collection('FlashCards')
        .get()
        .orderBy('customId');
      setCards(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
    };
    fetchData();
  }, []);

But when I do this I get the following error:

orderBy is not a function

How can I order my data by customId?

like image 920
user1941537 Avatar asked Jun 09 '26 21:06

user1941537


1 Answers

Hi try to switch “orderBy” and “get”

like image 54
Davide Consonni Avatar answered Jun 11 '26 10:06

Davide Consonni