(Struggling with storing multiple images in an array using Vue and Firebase)

I'm experimenting with an image slider and I want to streamline the process by uploading images to Firestore and storing them in an array to feed into the slider. I already have code for image uploads, but I'm facing a challenge. Instead of a single file input, I added three thinking I could save the image URLs in an array. However, only the first image is being uploaded and stored, while the rest are not.

How can I resolve this issue?

Importing Slider Images

<form @submit.prevent="handleSubmit">
      <h4>Create New Content</h4>
      <input type="text" required placeholder="Insert Title" v-model="sliderTitle">
      <label>Choose Images for Your Slider</label>
      <input type="file" @change="handleChange">
      <input type="file" @change="handleChange">
      <input type="file" @change="handleChange">
      <div class="error">{{ fileError }}</div>
      <button v-if="!isPending">Create</button>
      <button v-else disabled>Saving...</button>
   </form>
</template>

<script>

import { ref } from 'vue'
import useStorage from '@/composables/useStorage'
import sliderCollection from '@/composables/sliderCollection'
import { timestamp } from '@/firebase/config'
import { useRouter } from 'vue-router' 

export default {
    setup() {
       const { filePath, url, uploadImage } = useStorage()
       const { error, addDoc } = sliderCollection('slider')
       const sliderTitle = ref('')
       const file = ref(null)
       const fileError = ref(null)
       const isPending = ref(false)
       const router = useRouter();

       const handleSubmit = async () => {
          if (file.value) {
             isPending.value = true
             await uploadImage(file.value)
             await addDoc({
                sliderTitle: sliderTitle.value,
                imageUrl: [url.value],
                filePath: filePath.value,
                createdAt: timestamp()
             })
             isPending.value = false
             if(!error.value) {
                router.push({ name: "Home" })
             }
          }
       }

       // allowed file types

       const types = ['image/png', 'image/jpeg']

       const handleChange = (e) => {
          const selected = e.target.files[0]
          console.log(selected)

          if (selected && types.includes(selected.type)) {
             file.value = selected
             fileError.value = null 
          } else {
             file.value = null
             fileError.value = 'Please select an image of the type JPG or PNG'
          }
       }

       return {
          sliderTitle,
          handleSubmit,
          handleChange,
          fileError,
          file,
          isPending
       }
    }
}
</script>

The Slider Itself

<template>
  <div v-for="content in slider" :key="content.id">
    <img :src="content.imageUrl" />
  </div>
</template>

    <script>
    const images = [];
    export default {
      props: ['slider'],
      name: "ImageSlider",
      data() {
        return { index: 0, imageUrl: images[0] };
      },
      methods: {
        next() {
          this.index = (this.index + 1) % images.length;
          this.imageUrl = images[this.index];
        },
        autoChangeSlide() {
          setInterval(() => {
            this.next();
          }, 3000);
        },
      },
      beforeMount() {
        this.autoChangeSlide();
      },
    };
    </script>

Answer №1

In order to upload multiple images in one request, make sure to include the 'multiple' keyword in the HTML code:

<input type="file" @change="handleChange" multiple>

Next, iterate through the files to upload multiple images:

await Promise.all(files.map(async file=>{
if (file.value) {
             isPending.value = true
             await uploadImage(file.value)
             await addDoc({
                sliderTitle: sliderTitle.value,
                imageUrl: [url.value],
                filePath: filePath.value,
                createdAt: timestamp()
             })
             isPending.value = false
             if(!error.value) {
                router.push({ name: "Home" })
             }
          }
}))

I hope this explanation clarifies the process for you, as your initial question was a bit unclear. It's possible that my interpretation is affected by a language barrier.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Ajax success callback unexpectedly displays the number "1" in the top left corner of the empty page instead of updating the specified div

Currently, I am in the process of developing a Yii2 application. I have encountered an issue where I select data from a Bootstrap modal popup and submit it to a controller action that contains an insert query. The problem arises after submitting the data f ...

Let's discuss how to include the scrollTop option

I am new to coding and I need help adding a scrollTop margin of +100px to my code. The page already has some top margin but I can't seem to locate it. I'm also having trouble finding where the margin-top is being set in the JavaScript file. /*** ...

Automatically refresh the browser upon changes in file content, utilizing Node.js for saving

Currently, I am immersed in a project using node.js. One of my main requirements is to be able to load a .txt file on the browser and have its content updated whenever changes are made and saved. Additionally, I would like the browser to automatically re ...

What is the process for implementing a title search filter in Vue.js?

Hey there, hoping you're having a good night! I've been trying to set up a bookstore using Vue.js with code retrieved from a Json api. However, I'm encountering some issues with the "computed" property. Here's the code snippet: new Vue ...

The underscore convention for defining members in Typescript allows for clear and concise

Let's talk about a class called Email class Email { private _from: string; private _to: Array<string>; private _subject: string; } When an email object is created, it will look something like this: { _from:'', _to:'&apo ...

Navigating the Terrain of Mapping and Filtering in Reactjs

carModel: [ {_id : A, title : 2012}, {_id : B, title : 2014} ], car: [{ color :'red', carModel : B //mongoose.Schema.ObjectId }, { color ...

Instructions for creating a distinct click listener for each <img> element inside a table cell

Within my table, each row contains multiple columns with images as data. I successfully implemented a 'common listener' that is triggered when any image within a table row is clicked. $('#mytable tbody td img').click(function () { // ...

Long taps do not activate the context menu in the mobile interface, as noted in the Google Maps API

During the development of my project, I encountered an issue with the Google Maps API not functioning correctly on mobile devices. I am utilizing GMaps.js, but even that example does not properly support right-click (long tap event). Here is a snippet of ...

Encountering an error message stating "Unable to read property 'map' of undefined while attempting to create drag and drop cards

I have incorporated the library available at: https://github.com/clauderic/react-sortable-hoc The desired effect that I am aiming for can be seen in this example: https://i.stack.imgur.com/WGQfT.jpg You can view a demo of my implementation here: https:// ...

Discovering the value of a variable within an object using JavaScript

Here is the code snippet I am working with: for (var i = 0; i<ke.length; i++) { var ar = ke[i]; var temp = {ar :(n[a])}; //how to resolve a console.log(temp); } The 'temp' object is supp ...

What is the best way to refresh flexslider after it has been updated via AJAX?

At first, my slider is functional upon loading the page. However, after making an ajax call and receiving new slides to populate the slider, it becomes deactivated (as expected) https://i.sstatic.net/LC0yG.png Is there a method to reinitialize the flexsl ...

Reveal or conceal information with a dropdown menu feature

I am attempting to implement a feature where the image file upload section is hidden or displayed based on the selection made in a dropdown list. If the user selects option "2", the image upload section should be hidden. Conversely, if they choose option " ...

Using three.js lookAt() to align a local axis that is not the positive Z axis towards a different object

Currently, I am in the process of developing an application in which a character (depicted as a cone shape for now) is positioned on a specific surface (currently represented by a cylinder placed horizontally). My goal is to have the character's feet ...

Exploring the possibilities of utilizing dynamic components in Nuxt.js 3

I am attempting to display dynamic components but it is not functioning as expected. <component :is="comp" /> The variable comp contains the name of the component during the process (CardComponent). No error messages are being shown and n ...

Updates to the visibility of sides on ThreeJS materials

When viewed from the back, the side is hidden as desired, but I am struggling to determine if it is visible from the renderer or camera. new THREE.MeshBasicMaterial({ map: new, THREE.TextureLoader().load('image.jpg'), side: THREE. ...

Unable to configure raycaster layers within Three.js framework

While attempting to configure the raycaster layer to only cast on a single layer, as outlined in the threejs documentation: - I encountered the following error Uncaught TypeError: Cannot read properties of undefined (reading 'set') What could b ...

adjusting the height of a div using jQuery UI's layout feature

Recently, I have been playing around with the adjustable grids plugin (jquery ui layout) to set the width of each div using the plugins. However, I've encountered a challenge when it comes to adjusting the height of inner divs within the layout. Speci ...

Issue encountered while serializing the `.product` object retrieved from the `getStaticProps` function in NextJS, in conjunction with

I ran into an error message saying "Error: Error serializing .product returned from getStaticProps in "/products/[id]". Reason: undefined cannot be serialized as JSON. Please use null or omit this value." This issue occurred while I was attempting to crea ...

Add a JQuery function to the button element in the HTML code

Currently, I am experimenting with AJAX to load a series of consecutive pages within a main page. The process is illustrated in the image below: Thanks to the guidance from this community, I have learned how to call content from other pages by utilizing t ...

"I'm looking for a way to store and fetch TypeScript objects with PouchDB. Any suggestions on

As someone who is new to typescript and web development, I am eager to incorporate PouchDB into my typescript project to store my objects. Despite the lack of documentation, I am struggling to find the correct approach. I have created typescript objects t ...