I have this data where I fetch all of the products in Firestore:
const [products, setProducts] = useState([]);
useEffect(() => {
let isMounted = true;
const getProducts = async () => {
const querySnapshot = await getDocs(collection(db, "products"));
const arr = [];
querySnapshot.forEach((doc) => {
arr.push({
...doc.data(),
id: doc.id,
});
});
if (isMounted) {
setProducts(arr);
setIsLoading(true);
}
};
getProducts().catch((err) => {
if (!isMounted) return;
console.error("failed to fetch data", err);
});
return () => {
isMounted = false;
};
}, []);
Example data of the product
:
I also have this searcList
so users can search any of the products, sizes, or categories. The problem here is that it does not immediately shows the data of the products
once it is mounted. I have to first type in a specific product and it will display the specific item, and when I click x
to clear the search
field that is the time it will display all of the products. However, if I change the searcList.map
to productList.map
, it will immediately render the products
const [searchList, setSearchList] = useState([]);
const [searchKey, setSearchKey] = useState("");
useEffect(() => {
let x = [...products];
x = x.filter((y) => {
const key = searchKey.toLocaleLowerCase();
const values = ["prodName", "size", "cat"];
return values.some((val) => y[val].toLocaleLowerCase().includes(key));
});
setSearchList(x);
}, [searchKey]);
const handleClear = () => {
console.log("clear");
setSearchKey("");
};
Displaying the searchList
with a map:
{searchList.map((item, index) => (
<List key={index}>
<Paper>
<ListItemText
primary={item.prodName}
secondary={
item.size + "(Size)" + " - " + item.cat + "(Category)"
}
/>
<br />
</div>
))}
</Paper>
</List>
))}