I’m making a dashboard for my react native application and I want to fetch data from firebase. Users submit a form from the app and its sent to the firebase. I have 4 collections, but here only 2 are important. The users collection and the counters collection.
counters collection
users collection
Each time a user submit a form, the counter increases by 1. I want to fetch that number to be shown in a table next to the user.
E.g.: User – Trip Count: 10
import React, { useState, useEffect } from 'react';
import { Table } from 'antd';
import { db } from '@/config/firebase';
import { doc, getDoc, collection, getDocs } from 'firebase/firestore';
const UserTripList = () => {
const [usersWithTripCounts, setUsersWithTripCounts] = useState([]);
useEffect(() => {
const fetchUsersWithTripCounts = async () => {
try {
console.log('Fetching users with trip counts...');
const usersRef = collection(db, 'users');
const usersSnapshot = await getDocs(usersRef);
const usersData = [];
for (const userDoc of usersSnapshot.docs) {
const userId = userDoc.id;
console.log(`Fetching trip count for user ${userId}...`);
const tripCount = await fetchTripCount(userId);
console.log(`Trip count for user ${userId}: ${tripCount}`);
usersData.push({ id: userId, tripCount });
}
console.log('Fetched users data:', usersData);
setUsersWithTripCounts(usersData);
} catch (error) {
console.error('Error fetching users with trip counts:', error);
}
};
fetchUsersWithTripCounts();
}, []);
const fetchTripCount = async (userId) => {
try {
const counterDocRef = doc(db, 'counters', userId);
const counterDocSnapshot = await getDoc(counterDocRef);
if (counterDocSnapshot.exists()) {
return counterDocSnapshot.data().tripCount || 0;
} else {
return 0;
}
} catch (error) {
console.error('Error fetching trip count for user', userId, error);
return 0;
}
};
const columns = [
{
title: 'User ID',
dataIndex: 'id',
key: 'id',
},
{
title: 'Trip Count',
dataIndex: 'tripCount',
key: 'tripCount',
},
];
return (
<div style={{ padding: '20px' }}>
<h1 style={{ marginBottom: '20px' }}>User Trip List</h1>
<Table dataSource={usersWithTripCounts} columns={columns} rowKey="id" />
</div>
);
};
export default UserTripList;
The users are fetched correctly, I can see their email, but the trip count it’s always 0. It’s 5 in the morning and can’t figure it out.
Note: I have a similar table in the app where I use orderBy to order the trips in a list based on the current Auth user.