The combination of Firebase Storage's listAll() method and getDownloadURL() function is not functioning properly

I created a function in my utils file that is designed to find and retrieve the URLs of images stored within a specific folder on Firebase Storage. The folder path is "proj_name/screenshots/uid/" and it contains 8 images. I have imported this function into a Next.js [id] page using getServerSideProps(). However, when I try to output the length of the URL array using console.log, it always shows 0. What could be causing this issue?

Here is the code from the Utils file:

...
export const getImages = async (dir) => {
  let data = []
  const storage = getStorage()
  const listRef = ref(storage, dir)
  
  await listAll(listRef)
    .then(res => {
      res.items.forEach(itemRef => {
        getDownloadURL(itemRef)
          .then(url => {
            data.push(url)
          })
      })
    })
    
  return data
}

And here is the code from the Next.js page file:

import { getItems, getImages } from "../../utils/firebase"

export const getServerSideProps = async (context) => {
  const id = context.params.id
  const item = await getItems(id)
  const screenshots_urls = await getImages('proj_name/screenshots/' + id)
  
  return{
    props: { item, screenshots_urls }
  }
}

const Details = ({ item, screenshots_urls }) => {
  return (
    <>
      {
        console.log(screenshots_urls.length)
      }
    </>
  )
}
 
export default Details

Answer №1

In my opinion, it is advisable to choose either the async-await approach or utilize promise chaining exclusively without mixing both. Consider revising the code snippet below for better clarity:

const fetchImages = async (directory) => {
  let imagesData = []
  const storage = getStorage()
  const listReference = ref(storage, directory)
  const result = await listAll(listReference)

  const promisesList = result.items.map((itemRef) => getDownloadURL(itemRef))
  imagesData = await Promise.all(promisesList)
  console.log(imagesData)

  return imagesData
}

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

Updating Values in Nested Forms with Angular Reactive Form

I have been grappling with a form setup that looks something like this: itemEntities: [ {customisable: [{food: {..}, quantity: 1}, {food: {..}, quantity: 5}]}, {customisable: [{food: {..}, quantity: 0}]}, ] My challenge lies in trying to u ...

Display various React components for widgets

I am looking to display multiple instances of a widget in html. I have 3 divs with the same id, each with different attributes, and I want to render my react component three times on the page. Currently, I am only able to display the first component. Here ...

What steps do I need to follow to upload an image file through Socket.IO?

For my school project, I am developing a chat application and facing a challenge with implementing an onClick event to trigger a function that utilizes socket-io-file-upload to prompt the user to select a file for upload. This functionality is detailed in ...

Upon initial login, React fails to retrieve notes

I developed a note-taking React app using the MERN stack with React Router DOM v6. When I initially visit the website, I am directed to the login page as intended. However, upon logging in, the page refreshes but does not redirect to the home page. This is ...

Boost your website's loading time by utilizing the async and defer attributes

Looking to enhance the speed of my webpage, particularly focusing on improving initial page speed. Research suggests that using the async and defer attributes for JavaScript can be beneficial. All JavaScript scripts are currently placed just above the cl ...

Utilizing Rails for dynamic form validation with AJAX

As someone who is new to jQuery, AJAX, and JavaScript in general, I am facing a challenge with front-end validation for a Rails form that utilizes an ajax call to query the server. The validation works fine when I am debugging, giving enough time for the A ...

Retrieving exclusive npm packages from an npmjs user

I am currently facing a challenge with transferring all of our npm modules from npmjs.com to a new location. The issue is that our modules are saved under a private npm user account, making it difficult for me to programmatically access and consume all the ...

I am having trouble displaying my favicon.ico file on my website, even though I have made sure to set it as public and included

export const metadata: Metadata = { title: "title", description: "description", icons: { icon: "/favicon.ico", }, }; This code snippet is from the globalLayout file located at /app/layout.tsx. In this project, an ...

Uploading images with Laravel and VueJS

I am having trouble with Vuejs image upload. My backend is Laravel, but for some reason the images are not being sent to the Controller. <form method="POST" class="form-horizontal" role="form" v-on:submit.prevent="updateProduct(editProduct.id)" en ...

When attempting to run the Firebase app on a mobile phone, the results indicate that the app is successfully running. However, the

My Firebase app is designed to send messages to the Firebase database. When I run it on my mobile phone, Android shows that the app runs successfully with no logcat errors. However, the app icon does not appear on the mobile phone's icon list. Interes ...

When a new entry is added to the database, automatically refresh a <div> section within an HTML document

I have a basic webpage that showcases various products stored in the database. My goal is to implement an updater feature where, if a user adds a new product, the page will automatically display the latest addition in a specific div. I attempted to refere ...

How can I implement the useState hook in server side rendering with Next.js?

Seeking a way to pass a value from the client side to the server side has been challenging. While useState is not available for use on the server side, there must be an alternative solution. The goal is to fetch a value from the client and incorporate it ...

What sets array of middlewares apart from compose-middleware?

Someone recommended that I utilize the compose-middleware module in order to have an array of middlewares. After trying it out, I discovered that it works seamlessly with express.js: router.post('/editPassword', doAction ); var doAction = [ ...

Pass a bespoke object back to the GraphQL resolver

In my Node-Express backend server with GraphQL setup, I am working on providing a custom object as output for a GraphQL resolver. The usual Sequelize approach hasn't worked for me in this case, so I'm exploring new methods. const RootQueryType = ...

How to calculate large integer powers efficiently in JavaScript using the mod

I'm currently on the lookout for a reliable JavaScript algorithm as I attempted to implement one using node.js : function modpow_3(a,n, module){ var u = BigInt('1'); var e = equals(a, u); if( e) return a; if(equalsZero(a)) return a; if(pair ...

Embed a div element within a content-editable area

Is there a way to add a div with text to a contenteditable element and automatically select the text between the div tags after inserting the div? div.innerHTML +='<div id="id">selecttext</div>' I have tried this method, but it does ...

What causes the fixed div to appear when scrolling horizontally?

I have replicated this issue in a live example: http://jsfiddle.net/pda2yc6s When scrolling vertically, a specific div element sticks to the top. However, if the window is narrower than the wrapper's width and you scroll horizontally, the sticky elem ...

navigate a specific web address using Express routing

Is there a specific regex pattern that should be used in an Express application to match a URL? For example, if the endpoint is www.mydomain.com/v1/https://www.url-to-be-matched.com. I am aiming to accept https://www.url-to-be-matched.com as parameters. H ...

Set a maximum height for an image without changing its width dimension

I am facing an issue with an image displayed in a table. The image is a graph of profiling information that can be quite tall (one vertical pixel represents data from one source, while one horizontal pixel equals one unit of time). I would like to set a ma ...

The field 'shouldComponentUpdate' cannot be reassigned to itself

I encountered a TypeScript error while using shouldComponentUpdate: The error message states: "Property 'shouldComponentUpdate' in type 'Hello' is not assignable to the same property in base type Component<IProps, any, any>." ...