So I have my main functional component IndexHeaderHome and I am trying to set the state allDeals, and then pass that state as props into the component Tabs. For some reason tho I am getting this map undefined error and after a bit of tinkering I am unable to figure out a solution, I am hoping someone can point out where I am going wrong. Thanks so much =]
function IndexHeaderHome() {
const pageHeader = React.useRef();
const [allDeals, setAllDeals] = React.useState();
React.useEffect(() => {
if (window.innerWidth > 991) {
const updateScroll = () => {
let windowScrollTop = window.pageYOffset / 3;
pageHeader.current.style.transform =
"translate3d(0," + windowScrollTop + "px,0)";
};
window.addEventListener("scroll", updateScroll);
return function cleanup() {
window.removeEventListener("scroll", updateScroll);
};
}
// no deps array makes it so the effect runs on every render
// an empty one will run only on mount
}, []);
// Ive never used firebase, but I'm guessing you want
// to initialize firestore only once and put it in a ref
useEffect(() => {
const getStuff = async () => {
const db = firebase.firestore();
let citiesRef = db.collection("Live_Deals");
let query = citiesRef
.where("liveDiscountActive", "==", true)
.get()
.then((snapshot) => {
if (snapshot.empty) {
console.log("No matching documents.");
return;
}
snapshot.forEach((doc) => {
console.log(doc.id, "=>", doc.data());
let data = doc.data();
let deals = JSON.parse(data);
setAllDeals(deals);
});
})
.catch((err) => {
console.log("Error getting documents", err);
});
};
}, []);
const [iconPills, setIconPills] = React.useState("1");
const [pills, setPills] = React.useState("1");
return (
<>
<div className="page-header clear-filter" filter-color="blue">
<div
className="page-header-image"
style={{
backgroundImage: "url(" + require("assets/img/header.jpg") + ")",
}}
ref={pageHeader}
></div>
<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br />{" "}
<br /> <br /> <br />
<Container>
<div className="content-center brand">
<h1 className="h1-seo">Get updates on the latest deals!</h1>
<h3>Save money everyday with our live deal updates!</h3>
</div>
</Container>
<Container>
<FilterNow />
{allDeals.map(() => (
<Tabs
DealName={discountName}
DealDisc={discountDesc}
DealEnd={discountEdate}
DealCat={discountDesc}
DealDisp={discountDisp}
/>
))}
</Container>
</div>
</>
);
}
export default IndexHeaderHome;
the error is on this line here
{allDeals.map(() => (
2
Answers
You set
allDeals
to null by default by usinguseState()
just null check it and you will be fine;
P.S: Ideally you might want to render spinner or some kinda loading component while it is loaded asyncronously
You will need to add a null checking or an initial state on that.
Example of null checking
With initial State