I have a school project, where I have to use Firestore for the first time, without a teacher really knowing how to do it either. I have made a budget/subscription app, where I want to create my total subscriptions for a list sort of. I have linked my Firestore and it runs as intended. But I have like 10 subs with name, price, date and category. But I get 8k reads a minute?? I have recently tried to the pay as I go plan, but I am afraid I will be charged a ton, if I don't get it fixed asap. Anyone that can help me with this emergency? First question on here, so sorry if I'm doing it wrong. I am using react.
Here is the code for my crud component:
import { useState, useEffect } from "react";
import { db } from "../firebase-config";
import { collection, getDocs, doc, deleteDoc } from "firebase/firestore";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import { Button } from "react-bootstrap";
export default function Crud() {
const [subs, setSubs] = useState([]);
const subsCollectionRef = collection(db, "subs");
const deleteSubs = async (id) => {
const subsDoc = doc(db, "subs", id);
await deleteDoc(subsDoc);
};
useEffect(() => {
const getSubs = async () => {
const data = await getDocs(subsCollectionRef);
setSubs(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};
getSubs();
}, [subsCollectionRef]);
return (
<div className="App">
{subs.map((subs) => {
return (
<div className="subField">
{""}
<div className="field">
<h1>
<Button sx={{ fontSize: 25 }} style={{ backgroundColor: "rgba(255, 255, 255, 0.888)", border: "none"}}
onClick={() => {
deleteSubs(subs.id);
}}
<MoreVertIcon style={{ color: "black"}} ></MoreVertIcon>
</Button>{" "}
 {subs.name}
</h1>
<h1>DKK Første betaling: {subs.payment} <br></br> Pris: {subs.price} DKK</h1>
</div>
</div>
);
})}
</div>
);
} `
How do i reduce it properly? I feel like i have read a lot of articles about how to reduce it, but i havent figured anything out i completely understand.. And not for my specific instance atleast. Link to Github
CodePudding user response:
You don't need to add the CollectionReference
to dependencies array. If you log something in getSubs
function then you can see it's fetching data from Firestore multiple times. Try:
useEffect(() => {
const getSubs = async () => {
console.log('getSubs function running');
const data = await getDocs(subsCollectionRef);
setSubs(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};
getSubs();
}, []); // <-- remove subsCollectionRef