Reputation: 127
I'm working on e-commerce website in react js and use Firebase Realtime Database as backend. i'm trying to get datas from RTDB and want to show on react js website.
here is my RTDB structure image(1)
this is the data that i stored..(image(2))
In above image(1), i stored my Parent node value (/Pant/Formal Pant(Blue Line) -> into caac442a-66fe-ba7e(Red line)). I did this from both node (Pant and Shirt). i'm able to get that data by manually type my path but not able to get data by dynamically.
Here is my code for read data from realtime databse.
// read data
const [itemData, setItemData] = useState([]);
const readData = () => {
onValue(ref(database, `/products/Shirt/Formal Shirt`), (snapshot) => {
setItemData([]);
const data = snapshot.val();
if (data !== null) {
const objectData = Object.values(data);
console.log(objectData);
setItemData(objectData);
}
});
};
try to map data in this...
/* -----trying to read data here----- */
{itemData.map((item) => {
return (
<div className="item-category-data-list">
<div className="item-type">
<h2>{item.category}</h2>
<h3>view all</h3>
<div className="item-container-list">
<div
className="item-data-container"
key={item.uuID}
onClick={() => updateData(item)}
>
<img className="item-photo" src={item.image1} alt=""></img>
<div className="item-data">
<p className="name">{item.productName}</p>
<p className="style">{item.type}</p>
<p className="item-price-row">
<p className="item-discount-price">
₹{item.discountPrice}
</p>
<p className="item-original-price">
₹{item.originalPrice}
</p>
<p className="item-discount">({item.discount})</p>
</p>
<div className="rating-section">
<FontAwesomeIcon className="star-icon" icon={faStar} />
<p className="rating">4.7</p>
<p className="rating-people">(8.4K)</p>
</div>
<p className="item-id">ID: {item.uuID}</p>
</div>
</div>
</div>
</div>
</div>
);
})}
I want to map this data and want to read in my web site. Please give me some solution to solve this problem.
Upvotes: 1
Views: 280
Reputation: 598740
I'm not sure what you mean by "getting path dynamically", but if you want to read all products - you can do that by reading from products
, and then navigating the resulting data snapshot.
Something like this:
onValue(ref(database, `/products`), (snapshot) => {
setItemData([]);
snapshot.forEach((categorySnapshot) => {
categorySnapshot.forEach((productSnapshot) => {
const data = productSnapshot.val();
if (data !== null) {
const objectData = Object.values(data);
console.log(objectData);
setItemData(objectData);
}
}
}
});
If you want to store all items as an array, that'd be:
onValue(ref(database, `/products`), (snapshot) => {
setItemData([]);
let items = [];
snapshot.forEach((categorySnapshot) => {
categorySnapshot.forEach((productSnapshot) => {
const data = productSnapshot.val();
if (data !== null) {
const objectData = Object.values(data);
items.push(objectData);
}
})
})
setItemData(items);
});
Upvotes: 1