setDoctorDetails Not working. I try to set it after getting data from cloud firestore. I am using react native and struggling to find the problem
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import { collection, query, where, getDocs } from 'firebase/firestore';
import { db } from '../../firebase/firebaseCofig';
export default function FilteredDoctorsScreen({ route, navigation }) {
const { specialist } = route.params;
const [doctorDetails, setDoctorDetails] = useState([]);
useEffect(() => {
(async function () {
const q = query(
collection(db, 'Doctors'),
where('specialist', '==', specialist)
);
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
setDoctorDetails(doc.data());
});
console.log('DoctorDetails', doctorDetails);
})();
}, []);
return <Text>FilteredDoctorsScreen</Text>;
}
CodePudding user response:
querySnapshot.forEach((doc) => {
setDoctorDetails(doc.data());
});
Every time through this loop, you're overwriting the previous state, so you'll only end up with the data from the last doc. If you want an array of all data, do this
setDoctorDetails(snapshot.docs.map(doc => doc.data()))
P.S, the following log statement will always log out the old state, not the new state:
console.log('DoctorDetails', doctorDetails);
So if you want to log out the new state, either assign it to a variable and log out that variable:
const newDoctorDetails = snapshot.docs.map(doc => doc.data());
cvonsole.log('newDoctorDetails', newDoctorDetails);
setDoctorDetails(newDoctorDetails);
Or put your log statement in the body of the component so it can log out when the component rerenders.
const [doctorDetails, setDoctorDetails] = useState([]);
console.log('rendering', doctorDetails);