So I have this app using Ionic React and Cloud Firestore as the Database. Mostly I use these codes to retrieve data:
const [teacher, setTeacher] = useState('');
const history = useHistory();
const [users, setUsers] = useState([{}]);
async function obtainData() {
const querySnapshot = db.collection('TEACHER_DATA').where('email', '==', Cookies.get('email'));
const awaitSnapshot = await querySnapshot.get();
const data = awaitSnapshot.docs.map(doc => doc.data().name);
setTeacher(String(data));
const querySnapshot2 = db.collection('CLASS').where('class_teacher', '==', teacher);
const awaitSnapshot2 = await querySnapshot2.get();
const data2 = awaitSnapshot2.docs.map(doc => doc.data());
setUsers(data2);
}
obtainData();
return (
<div>{
users.map((value: any, index) => (
<IonCard key={index} onClick={() => {
Cookies2.set('id', value.student_id);
history.push({
pathname: '/Student_biodata',
state: value.student_id
})
}} class="students">
<IonCardTitle>
{value.class_student}
</IonCardTitle>
{value.branch}
<IonCard id="mini-picture">
<IonImg src={'/assets/propic/' + value.student_id + '.jpg'}></IonImg>
</IonCard>
</IonCard>
))}
</div>
);
This code shows the data I needed. However, when I checked the Firestore Usage, in 15 minutes it already has 6K reads. This is not suitable if someday the user number is increasing. My app will reach the daily limit quota in no time. The documents in my Firestore project is less than 30.
Is there any solution for me to reduce the read in Firestore? Is there any example to make a better structure in NoSQL Firestore to reduce the read? I've watched the tutorial videos from Firebase about Firestore yet I still don't get it.
The problem is that you are calling
obtainData
on every render of the page, instead of just once when the page is loaded. You can use theuseEffect
to function similar tocomponentDidMount
See the documentation on conditionally firing the effect which might be needed if you want the call to only happen when one of the parameters change https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect