user1941537
user1941537

Reputation: 6675

React - Ordering data coming from FireBase

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?

Upvotes: 3

Views: 36

Answers (1)

Davide Consonni
Davide Consonni

Reputation: 2124

Hi try to switch “orderBy” and “get”

Upvotes: 1

Related Questions