Unable to retrieve all URLs with getDownloadURL

Having an issue with my firebase storage upload - I am uploading three photos, but when I try to retrieve the firebase URL for each image using getDownloadURL, it only returns two objects instead of three.

        //const uploadedFilesURL = [];
        uploadToStorage.map((image) => {
            const storageRef = ref(storage, `images/${image.name + v4()}`);
            uploadBytes(storageRef, image).then((snapshot) => {
                getDownloadURL(snapshot.ref).then((url) => {
                    //console.log(image);
                    //console.log(url);
                    uploadedFilesURL.push({file: image, url})
                })
            });
        });

        console.log(uploadedFilesURL);

Oddly enough, when I log the image and URL individually, I get the three objects I need (although I don't want to log the image itself).

        const uploadedFilesURL = [];
        uploadToStorage.map((image) => {
            const storageRef = ref(storage, `images/${image.name + v4()}`);
            uploadBytes(storageRef, image).then((snapshot) => {
                getDownloadURL(snapshot.ref).then((url) => {
                    console.log(image);
                    console.log(url);
                    uploadedFilesURL.push({file: image, url})
                })
            });
        });

        console.log(uploadedFilesURL);

My goal is to extract the firebase URL path so that I can store it in a separate database as a reference, hence why I am creating the uploadedFilesURL object.

Thank you!

Answer №1

As pointed out by Doug, there is an issue in your code where it does not wait for all uploads and calls to getDownloadURL to finish before logging the results. One way to resolve this issue is to utilize Promise.all:

let promises = uploadToStorage.map((image) =>
  const storageRef = ref(storage, `images/${image.name + v4()}`);
  return uploadBytes(storageRef, image).then((snapshot) => {
    return getDownloadURL(snapshot.ref);
  })
);

Promise.all(promises).then((urls) => {
  console.log(urls);
});

Alternatively, if you are within an async context, you can use the following for the last part:

const urls = await Promise.all(promises);
console.log(urls);

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 variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

Cube area to be filled

I am struggling to fill a cube with colors as it is only getting half of the figure filled. I suspect there might be an issue with the cubeIndices, but I'm having trouble figuring out how to make it fill everything. While I know I could use a cylinder ...

Is it feasible to style individual letters in a word within an input field?

Is it possible to change the styling of individual letters in an input containing text? For example, if the word 'Test' is in the input, can I make the 'Te' bold while leaving the 'st' regular? Alternatively, perhaps I'd ...

The 'click' event is not triggering after adding elements to the DOM using AJAX

$(".btn-close").on('click', function () { alert('click'); var win = $(this).closest("div.window"); var winID = win.attr("id"); $(win).find("*").each(function () { var timerid = $(this).attr("data-timer-id"); ...

Implementing defaultProps in conjunction with withStyles

Currently, I am in the process of developing a component using material-ui withStylers and defaultProps. However, I have encountered an issue where the props of the component are not being retrieved in the styles objects unless they are explicitly passed t ...

Show the day of the week

I'm seeking a solution to display the upcoming Friday of each week within Wordpress. We were able to achieve this in the past using the code below on non-Wordpress platforms, but it seems outdated and no longer functional. For example: This week&apos ...

Is it possible for me to use an NPX tool to execute git clone command?

I am currently working on developing a personalized NPX tool that will install my custom npm package onto a locally hosted server. At the moment, I have a layout template that I want other users to replicate when they run my NPX command. Here is an exampl ...

"Cross-origin resource sharing problem while working with NodeJs, Express, and React on

Currently, I am working on a small project where I am using NodeJs and Express for the backend and React for the client side. In order to tackle CORS policy issues, I have implemented the "cors" npm package on the server side, but unfortunately, it doesn& ...

Tips on sorting items in React

Hey there, I'm a beginner at react and currently working on my first ecommerce website. My main concern is about filtering products by size. I'm struggling with the logic behind it. Any help or guidance would be greatly appreciated. I also attem ...

Tips for optimizing iframe loading times using the onload event

I am facing an issue with the timing of iframe loading while using a list of URLs as sources. I have created a child iframe and appended it to the DOM, then run the onload function for further processing. However, the time recorded for each iframe seems in ...

What is the best approach for managing routing in express when working with a static website?

Whenever a user navigates to mydomain.com/game, I aim for them to view the content displayed in my public folder. This setup functions perfectly when implementing this code snippet: app.use('/game', express.static('public')) Neverthel ...

Why is it that my jquery code seems to be struggling with calculating the count accurately?

I'm currently working on restricting keyword input on my website. My goal is to automatically add a 'span' tag to any keyword entered by a user, as shown in the example html code below. Although I can limit the number of words, the count i ...

Include an extra "array" in the complete AJAX POST data when submitting through x-editable

Struggling to include an array of objects in the post data for a group of bootstrap x-editable on my JSP page. The data is retrieved from a table and an array of objects is constructed. This array needs to be appended to the list of other values posted by ...

Generate a table framework by dynamically adjusting the number of rows and columns

I'm running into an issue with my implementation of nested for-loops to dynamically generate a table using JavaScript. For this particular scenario, let's assume numRows = 2 and numCols = 6. This is the code snippet in question: let table = $( ...

Connect the input field to a dictionary

Here is an input field: <input id="DeviceId" class="form-control deviceCatalog" data-bind="value:DeviceTemp, valueUpdate: ['blur']" required /> This input is connected to the following viewModel: var ViewModel = f ...

Implementing specifications throughout the entire nodejs route

In my Nodejs app, I have a RESTful API where I need to check for a user's role before sending a response with data or 404 error. apiRouter.route('/users') .get(function (req, res) { var currentUser = req.decoded; if(curr ...

tips for sending a chosen item to the Vujes API

How can I send the selected item from a dropdown to an API in Vue.js? <select :v-model="selectedRole" class="custSelect"> <option v-for="option in options" v-bind:value="option.value"> {{option.role}} </option> ...

What could be the reason for the scope being empty in my AngularJS application?

I'm new to Angular and I'm currently customizing the tutorial for my app. However, I'm facing an issue with adding routes to my app. The templates are not being read correctly and the controller seems to have some issues as well. In order to ...

Using ngTable within an AngularJS application

While working on my angularjs application, I encountered an issue with ngtable during the grunt build process. It seems that the references are missing, resulting in the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module pa ...

Tips for modifying string in key-value pairs on the client side (example using Paypal checkout demo)

Looking to integrate an online payment system into my small online business, I have decided on using PayPal. Their solution is user-friendly and can be found here: https://developer.paypal.com/demo/checkout/#/pattern/client However, I am facing an issue w ...