I have used react-simple-image-slider to build an image slider for my project. I fetch images from firestore and pass them in the slider properties. However, they dont show up the first time, but only if I re-render (not refresh). When I tried with hardcoded images it worked. Also, does anybody know how to make the background image fit into the slider? Thanks
Here is the code:
export const ProductPage = () => {
const {uniqueProductName} = useParams();
const [productImages, setProductImages] = React.useState([]);
const fetchProduct=async()=>{
const q = query(collection(db, "products"), where("uniqueName", "==", uniqueProductName));
const querySnapshot=await getDocs(q);
let data = null;
querySnapshot.forEach((doc)=>{
doc.data().img.forEach((image)=>{
productImages.push({'url': image})
})
})
setProductImages(productImages);
console.log(productImages);
}
React.useEffect(() => {
console.log(uniqueProductName);
fetchProduct();
});
return (
<div>
<Navbarr/>
<MainContainer>
<SliderContainer>
<SimpleImageSlider
width={896}
height={504}
images={productImages}
showBullets={true}
showNavs={true}
/>
</SliderContainer>
<InfoContainer>
</InfoContainer>
</MainContainer>
<Footer/>
</div>
)
}
For making the image background fit to slider, documentation says this, but I dont understand where to add it in my React app:
enter image description here
>Solution :
You need two main fixes:
const {uniqueProductName} = useParams();
const [productImages, setProductImages] = React.useState([]);
const fetchProduct = async () => {
const q = query(collection(db, "products"), where("uniqueName", "==", uniqueProductName));
const querySnapshot=await getDocs(q);
let data = null;
// You need to use a new array to trigger a re-render since arrays are objects
// with a reference memory address, and when React compares them it makes a shallow
// compare, it just checks if they are the same object ( same reference ),
// not they have the same properties or elements.
const imgs = []
querySnapshot.forEach((doc)=>{
doc.data().img.forEach((image)=>{
imgs.push({'url': image})
})
})
setProductImages(imgs);
}
React.useEffect(() => {
console.log(uniqueProductName);
fetchProduct();
},[]); // Add an empty array of deps, to make the fetch only on component mount,
// otherwise it will get stuck in a loop at each re-render.