Skip to content

"Cannot read property 'type' of undefined" error when media array is empty #118

@JoshiiSinfield

Description

@JoshiiSinfield

I'm using this project with Nuxt.

Upon component mounting my array of media is empty. I'm then populating it in the fetch method (i've tried beforeMount & mounted too).

Because the array is empty when mounting I'm getting
image
"Cannot read property 'type' of undefined"

Nuxt/Vue file to recreate:

<template>
  <div class="wrapper ">
    <div>
      <ul>
        <li
          v-for="(image, index) in lightboxMedia"
          :key="index"
          style="display: inline-block"
        >
          <img
            v-lazy="image.src || image.thumb"
            style="height: 150px"
            @click="openGallery(index)"
          >
        </li>
      </ul>
      <light-box ref="lightbox" :media="lightboxMedia" :show-light-box="false" />
    </div>
  </div>
</template>
<script>
export default {
  name: 'Lightbox',
  components: {
  },
  fetch () {
    this.getURL().then((value) => {
      console.log(value)
      this.lightboxMedia.push(
        {
          src: value,
          thumb: value
        })
    })
  },
  data () {
    return {
      lightboxMedia: []
    }
  },
  methods: {
    openGallery (index) {
      this.$refs.lightbox.showImage(index)
    },
    getURL () {
      // Here to mimic an API call to retrieve img url.
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          resolve('https://images.unsplash.com/photo-1617718875775-c5f9800b17fb?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1868&q=80')
        }, 2000)
      })
    }
  },
  head: {
    title: 'Lightbox test'
  }
}
</script>
<style>
</style>

Any help would be much appreciated.

Cheers,
Josh

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions