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>
</>
);
}***
CodePudding user response:
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.