Home > Blockchain >  How to use SimpleImageSlider in Reactjs with an array of images from firebase firestore
How to use SimpleImageSlider in Reactjs with an array of images from firebase firestore

Time:02-24

I have an array of images saved in my firebase firestore documents. I want to show all images as a slide show and i found this react package that does that, react-simple-image-slider.

My images are saved this way in firestore:

enter image description here

Now I am retrieving them this way in order to add them to the slider:

const [imgUrls, setIMGUrls] = useState([]);
  const imageList = []

firebase.firestore().collection("Properties").where("propertyID", "==", propID).get().then((snapshot) => {

  snapshot.forEach((doc) => {

    const {
      imageUrls,
      features
    } = doc.data();

    imageList.push({
      imageUrls: imageUrls,
    })

    setIMGUrls(imageList)
  })
})

and using the component this way:

                     <SimpleImageSlider
                      width={896}
                      height={504}
                      images={imgUrls}
                      showBullets={true}
                      showNavs={true}
                    />

but I am getting an error that reads

"TypeError: Cannot read properties of undefined (reading 'url')
    at SimpleImageSlider"

How can I fix that?

EDIT:

console.log(JSON.stringify(images))

enter image description here

CodePudding user response:

The images property should be array of objects where each object has a property url as mentioned in the usage section. Try refactoring the code as shown below:

const [imgUrls, setIMGUrls] = useState([]);


firebase.firestore().collection("Properties").where("propertyID", "==", propID).get().then((snapshot) => {
  // images from all documents in the snapshot 
  let images = []

  snapshot.forEach((doc) => {
    const { imageUrls } = doc.data();
    images = [...images, ...imageUrls.map(url => ({ url }))]
  })

  setIMGUrls(images)
})
  • Related