简体   繁体   中英

How to sort(orderBy) and display my date from Firebase

This is my code, i can display from firebase, but i cant sort, i want to sort by date(timestamp) if somebody know thanks in advance

i work on React Native app, and use FirebaseV9

***export default function Cases() {
    const [dataCases, setDataCases] = useState([]);

    const fetchData = async () => {
        let list = [];
        const querySnapshot = await getDocs(
            collection(database, 'cases')
        );
        querySnapshot.forEach((doc) => {
            list.push({ id: doc.id, ...doc.data() });
        });
        setDataCases(list);
    };
Í
    useEffect(() => {
        fetchData();
    }, []);

    return (
        <>
            <HomeHeader />

            <View>
                <Text className='text-white text-2xl ml-5'>Latest Cases</Text>

                <View>
                    <FlatList
                        data={dataCases}
                        renderItem={({ item, index }) => {
                            return <CasesData item={item} />;
                        }}
                    />
                </View>
            </View>
        </>
    );
}***

You need to use query() to build a Query and then orderBy() to add the QueryConstraint as shown below:

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

const querySnapshot = await getDocs(
  query(collection(database, 'cases'), orderBy("timestamp"))
  // orderBy("timestamp", "desc") for ordering in descending order
);

Checkout the documentation for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM