Guide to uploading multiple images to Firebase v9 storage and retrieving all download URLs to update them in a Cloud Firestore database with Vue.js

Screenshot of Vue Dev Tools Console Log Screenshot

Script Code:

 import firebase from "@/firebase";
    import {
      getStorage,
      ref,
      uploadBytes,
      getDownloadURL,
      updateDoc,
    } from "firebase/storage";
    export default {
      data() {
        return {
          imagesUrl: [],
        };
      },
      methods: {
        chooseFile() {
          document.getElementById("imgUpload").click();
        },
    
        uploadImage(e) {
          this.files.push(e.target.files[0]);
          this.images.push(URL.createObjetURL(this.files));
        },
        createCity: async function () {
          const docRef = firebase.addDoc(
            firebase.collection(firebase.firestoreDB, "cities"),
            {
              name: "Tokyo",
              country: "Japan",
            }
          );
    
          var photos = [];
    
          for (var i = 0; i < this.files.length; i++) {
            // files.values contains all the files objects
            const file = this.files[i];
            const storage = getStorage();
            const metadata = {
              contentType: "image/jpeg",
            };
            const storageRef = ref(storage, "temp/" + docRef.id + "/" + file.name);
    
            const snapshot = await uploadBytes(storageRef, file, metadata);
            const downloadURL = await getDownloadURL(snapshot.ref);
            photos.push(downloadURL);
          }
          await console.log(photos);
          await updateDoc(docRef.id, { photosURLs: photos });
        },
      },
    };

Console Log Data:

  • TypeError: Object(...) is not a function at VueComponent._callee$ (fragment.vue?262c:453:1) at tryCatch (runtime.js?96cf:63:1) at Generator.invoke [as _invoke] (runtime.js?96cf:294:1) at Generator.eval [as next] (runtime.js?96cf:119:1) at asyncGeneratorStep (asyncToGenerator.js?1da1:3:1) at _next (asyncToGenerator.js?1da1:25:1)

Answer №1

Avoid using the await keyword inside a for or forEach loop. Instead, refer to resources like this article or this Stack Overflow thread.

Consider utilizing Promise.all() in the following way (not tested):

  const promises = [];

  for (var i = 0; i < this.files.length; i++) {
    // files.values contains all the files objects
    const file = this.files[i];
    const storage = getStorage();
    const metadata = {
      contentType: "image/jpeg",
    };
    const storageRef = ref(storage, "temp/" + docRef.id + "/" + file.name);

    promises.push(uploadBytes(storageRef, file, metadata).then(uploadResult => {return getDownloadURL(uploadResult.ref)}))
    
  }

  const photos = await Promise.all(promises);

  await console.log(photos);
  await updateDoc(docRef, { photosURLs: photos }); // <= See the change here docRef and not docRef.id

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

Ensure that a form field is validated using a dynamically assigned name in Angular

Generating a dynamic form in the view involves iterating through an object containing various user questions. Each question has a unique attribute called formFieldName, which assigns a random string as the field name. <form name="includedForm.newReques ...

What is the best way to apply conditional hovering in styled components?

Is there a way to customize the hover effect of a component based on specific props? I want the background to change when hovering over it if certain props are set, but do nothing if different props are specified. export const Container = styled.div` ...

implementing datepicker on multiple textboxes in jQuery upon button click

I have the ability to show multiple text boxes using jQuery. I am now looking to add a datepicker to those text boxes. Any assistance in finding a solution would be greatly appreciated. Thank you in advance. ...

The most efficient method for loading RSS feeds using a combination of Ajax and server-side processing

When deciding on how to load and display a small RSS Feed on your homepage, would you opt for an Ajax (asynchronous) approach or something more server-side oriented (like using node.js)? I am aware of some of the advantages and disadvantages of each metho ...

Updating the border color on angular-archwizard's steps

I am utilizing angular-archwizard to create circular steps for navigation. When I click on different steps, I can see the circle step border change color (in my case, orange) until I click on the last step. Once I click on the last step, all the other step ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

What steps can I take to position tsParticles behind all other elements in my NextJS project?

In full disclosure, I am not a web developer, so my setup may be incorrect. Currently, the particles are covering all other elements on the page. I would like them to be positioned behind the rest of the elements and only show as a background. import Imag ...

Refresh the table with updated results by clicking on a link

I have a table displaying user suggestions. When the user clicks "read more," an AJAX call is triggered to mark the suggestion as read in the database. Currently, I use a closed envelope icon for new suggestions and an open envelope for read suggestions. ...

Is there a solution to rectify the error related to POST net::ERR_CONNECTION_REFUSED?

Every time I try to post via ajax, an error keeps popping up. Here are the snippets of my code: let xhr = new XMLHttpRequest() let data ={ "name": "test", "phone": "12345678", "email": &qu ...

The login page continues to show an error message for incorrect credentials unless the submit button is clicked

My current project involves a React component called "Signin.js". Within this component, there are login input fields as I am working on creating a login system using Node.js, Express.js, and MySQL. To achieve this, I have set up a post request that sends ...

Extracting Data from Multiple Pages Using Python 3 without Changing URL

Recently, I delved into the world of web scraping and decided to try my hand at grabbing data from various websites. Currently, I'm focused on scraping information from the site - Using selenium, I've managed to extract longitude and latitude da ...

Having difficulty including my JavaScript file located in /app/assets/javascripts when using Rails 4 and "//= require_tree ." in application.js

I'm currently attempting to implement a d3.js graph into my Rails 4 application by following a tutorial found on this website. The example application provided on GitHub works perfectly as expected. The issue I am facing is that when I try to recreat ...

Utilizing a JavaScript variable in Jquery for managing an mp3 playlist

I am working on implementing an album feature for the jPlayer that is already in use. Here is the current static code: $(document).ready(function(){ new jPlayerPlaylist({ jPlayer: "#jquery_jplayer_1", cssSele ...

Node.js used to create animated gif with unique background image

As I navigate my way through the world of node.js and tools like express and canvas, I acknowledge that there might be errors in my code and it may take me some time to grasp certain concepts or solutions. My current project involves customizing a variati ...

Issue with Mat-AutoComplete arising while utilizing a formArray

After adding a form array to account for multiple rows, I had to modify my definition from: shoppingCartList Observable<any[]>; to shoppingCartList: Observable<any[]>[] = [];. However, this change resulted in an error in my filter function whic ...

Restricting the input range with JQuery

Need assistance with limiting user input in a text box for amounts exceeding a specified limit. Attempted using Ajax without success, considering jQuery as an alternative solution. Any expertise on this matter? function maxIssue(max, input, iid) { v ...

Using Google Chart API to create stacked bar charts with annotations using symbols

I am trying to annotate the bars in my stacked bar chart with currency symbols for profit and costs. While I have been able to successfully annotate the bars without currency symbols, I am facing difficulties in displaying them with the $ prefix. Can anyo ...

What is the process for activating the currently active tab or link within the MDBNav component of MDBreact?

Here is the code snippet I am working with: import React from "react"; import { BrowserRouter } from 'react-router-dom'; import { MDBNav, MDBNavItem, MDBNavLink } from "mdbreact"; const CustomTabs = props => { return ( <BrowserRouter& ...

Submitting information to the server utilizing a POST request through jQuery

What I'm attempting to achieve: I am currently working on sending data to my server using the $.post jQuery shortcut. The issue at hand: It seems that my program is not entering my switch case, possibly due to a problem with sending the action prop ...

Tips for enabling item draggability following AJAX filtering operations

I have a draggable list of names that can be filtered using checkboxes. When a checkbox is checked, an ajax call is made to filter the names. The list is displayed in an accordion format as shown below: <div id="myAccordion"> <?ph ...