I am creating a button that loads more documents from firestore database but the problem arises that I am able to do it in useEffect and set the state to the data. When I try to do the same thing in on click event handler it gives me the error that you don’t have sufficient access as I am logged in I have the access so I was able to get the data from firestore.
Here is some code::
import React, { useEffect, useState } from "react";
import Container from "@mui/material/Container";
import Box from "@mui/material/Box";
import Typography from "../../subcomponents/Typography";
import Adcard from "../../subcomponents/Marketplace/Adcard";
import Button from "@mui/material/Button";
import Pagination from "../../subcomponents/Marketplace/PaginationComponent";
import { db } from "../../config/Config";
function Adspace({ Products }) {
const [data, setData] = useState(null);
const [lastDoc, setlastDoc] = useState();
useEffect(() => {
return db
.collection("Products")
.orderBy("MonthlyRate", "asc")
.limit(2)
.get()
.then((snapshot) => {
const ProductData = snapshot.docs.map((doc) => doc.data());
/* snapshot.docs.forEach((doc) => {
ProductData.push({ ...doc.data(), id: doc.id });
setData(ProductData);
}); */
setData(ProductData);
const lastDoc = snapshot.docs[snapshot.docs.length - 1];
setlastDoc(lastDoc);
});
}, []);
console.log(data);
console.log(Products);
const fetchData = () => {
db.collection(Products)
.orderBy("MonthlyRate", "asc")
.startAfter(lastDoc)
.limit(1)
.get()
.then((snapshot) => {
const ProductData = snapshot.docs.map((doc) => doc.data());
setData((PrevData) => [...PrevData, ProductData]);
const lastDoc = snapshot.docs[snapshot.docs.length - 1];
setlastDoc(lastDoc);
});
};
return (
<div>
<Container component="section" sx={{ mt: 8, mb: 4 }}>
<Typography variant="h4" marked="center" align="center" component="h2">
Rent Machines
</Typography>
</Container>
<Box
sx={{
m: 8,
display: "flex",
flexWrap: "wrap",
justifyContent: "flex-start",
}}
></Box>
<Container
component="section"
sx={{ mt: 8, mb: 4, display: "flex", justifyContent: "center" }}
>
{/* {data !== null ? <Adcard /> : ""} */}
{data !== null
? data.map((doc) => {
if (doc.Type === Products) {
return <Adcard data={doc} state={Products} key={doc.id} />;
} else if (Products === "All") {
return <Adcard data={doc} state={Products} />;
}
})
: ""}
</Container>
<Box textAlign="center">
<Button variant="contained" onClick={fetchData}>
Load More
</Button>
</Box>
</div>
);
}
export default Adspace;
And here is firestore database rules for this collection
match /Products/{userid}{
allow create:if request.auth.uid!=null
allow read: if request.auth.uid!=null
allow write:if request.auth.uid==userid
allow delete:if request.auth.uid!=null
}