I am pulling a list of people from a database. When I map the array into many different components it works and the data gets displayed correctly. But when i want to access an individual element of the list trainer[0].id it says that the data does not exist. My guess is that the database isn't ready but how can I await that?
Here is my code:
export default function TrainerInfo() {
const [trainer, setTrainer] = useState([]);
useEffect(() => {
const trainerCollectionRef = collection(database, "trainer");
const getTrainer = async () => {
const data = await getDocs(trainerCollectionRef);
setTrainer(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};
getTrainer();
}, []);
return (
<div className="cms-stats">
<TrainerSelection>
{trainer.map(t => <Trainer id={t.id} key={t.id}>{t.name}</Trainer>)}
// works
</TrainerSelection>
<Info id={trainer[0].id} name={trainer[0].name} status={trainer[0].status} image={trainer[0].image} key={trainer[0].id}/>
// does not work
</div>
)
}
Thanks