Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
La matriz devuelta evaluada más tarde desde las llamadas asíncronas de Firestore no se actualiza en React

Parece que la matriz de "imágenes" primero está vacía y los elementos se agregan más tarde cuando se obtienen los datos de Firestore, pero el estado React no se actualizará, por lo que no se muestra ninguna imagen, aunque solía esperar en todas partes posible.

 useEffect(() => { async function getAllImages() { const images = await imageStorage.downloadAllImages(true); // images is first empty and then populated after the html has been rendered setImages(images); } getAllImages(); }, []);

mostrar imágenes:

 const handleGetImages = (images) => { console.log("images", images); // image is first empty and then populated after the html has been rendered return images.map((imageData) => { return ( <Grid.Column key={imageData.url}> <span class="image left"> <img src={imageData.url} style={styles.image} alt="" /> </span> </Grid.Column> ); }); };

imageStorage.js

 export async function downloadAllImages(thumbnail) { const imageRef = collection(db, "images"); console.log("hi"); var images = []; const q = query(imageRef, orderBy("date", "desc"), limit(10)); const querySnapshot = await getDocs(q); querySnapshot.forEach(async (doc) => { var imagePath = doc.data().ref; // image/task/... if (thumbnail) imagePath = imagePath.replace("images", "thumbnails"); // GET metadata of the image const imageRef = ref(storage, imagePath); // GET [imagePrefix] URL const url = await getDownloadURL(imageRef); const fullMetadata = await getMetadata(imageRef); images.push({ path: imagePath, url: url, metadata: fullMetadata.customMetadata, }); }); return images; }

Cualquier forma de arreglar esto? ¡Gracias!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Su código está cerca. Sin embargo, Array.prototype.forEach es síncrono. Sospecho que su función downloadAllImages no está esperando que se completen las devoluciones de llamada de bucle y devuelve la matriz de images que aún no se ha completado.

Refactorice la lógica para crear una matriz de Promises ( las funciones de devolución de llamada async ) y espere Promise.all , luego tendrá una matriz completa de imágenes para devolver.

 export async function downloadAllImages(thumbnail) { const imageRef = collection(db, "images"); const q = query(imageRef, orderBy("date", "desc"), limit(10)); const querySnapshot = await getDocs(q); // Map querySnapshot docs to array of async functions (Promises) const imageRequests = querySnapshot.docs.map(async (doc) => { const imagePath = doc.data().ref; // image/task/... if (thumbnail) imagePath = imagePath.replace("images", "thumbnails"); // GET metadata of the image const imageRef = ref(storage, imagePath); // GET [imagePrefix] URL const url = await getDownloadURL(imageRef); const fullMetadata = await getMetadata(imageRef); // Return image objects return { path: imagePath, url: url, metadata: fullMetadata.customMetadata, }; }); // Return array of resolved promises (ie the image objects) return Promise.all(imageRequests); }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!