I am doing a covid app in react with firestore database. I am new to this firebase. For this app, I have created a collection in firestore named 'VaccinationCentre'. In that I have given 4 fields that are 'State,District,Centrename,NoofDose'.
I have attached an image where I have 2 cards for the 2 documents which I have added in the collection. My aim is to update the 'NoofDose' in each card by decreasing the value by 1 when ever the button 'apply' is clicked.For eg, if the NoofDose is 100 , after I click the button 'apply' it should show as 99 without manual refresh.I have tried but I was not able to update each document. I was not able to do that.I have inserted the code for your reference. Kindly help with this.
function SearchVaccinCenter() {
const history = useHistory();
const auth = getAuth();
const user = auth.currentUser;
const db = getFirestore();
const [data, setData] = useState([]);
if (!user) {
return <Redirect to="/login" />
}
function back() {
history.push("/UserHome")
}
async function fetchdata() {
const querySnapshot = await getDocs(collection(db, "VaccinationCentre"));
const mapdata = querySnapshot.docs.map((e) => {
return {
centername: e.data().Centrename,
district: e.data().District,
state: e.data().State,
noofdose: e.data().NoofDose,
}
})
setData(mapdata);
console.log(mapdata);
}
function ApplyForVaccination() {
const database = getFirestore(); // initialize Firestore
const docRef = doc(database, "VaccinationCentre", "Jtu2QyO1jxmhUl9mKZOc");
console.log(doc.id);
const data = {
NoofDose: 50
};
updateDoc(docRef, data)
.then(response => {
console.log("Value of an Existing Document Field has been updated");
})
.catch(error => {
console.log(error.message);
})
}
return (
<div style={{height:"600px"}}>
<div className="continer">
<nav className="navbar navbar-light bg-dark">
<div className="container-fluid">
<button style={{color:"white",backgroundColor:"grey"}} className="btn btn-outline-secondary" onClick={back}>Back</button>
<div className="d-flex">
<button style={{color:"white"}} type="button" className="btn btn-white">Hello {user.displayName}</button>
</div>
</div>
</nav>
</div>
<div style={{marginTop:"20px"}} className="col-md-12 text-center">
<button className="btn btn-primary btn-lg" type="button" onClick={fetchdata}>Press to search</button>
{data.map((element, index) => {
return (
<div key={index} style={{width:"500px",margin:"50px 0px 0px 380px"}} className="card border-secondary mb-3">
<div style={{backgroundColor:"aliceblue"}}>
<h4 className="card-title ms-3"><b>No of Dose : {element.noofdose}</b></h4>
<div className="card-body">
<h6>State : {element.state}</h6>
<h6>District : {element.district}</h6>
<h6>Centre Name : {element.centername}</h6>
{console.log(element.state)}
<button className="btn btn-success btn-sm" type="button" onClick={() => ApplyForVaccination()}>Apply</button>
</div>
</div>
</div>
)
})}
</div>
</div>
)
}
export default SearchVaccinCenter;