Home > OS >  display data from firebase storage in reactjs
display data from firebase storage in reactjs

Time:10-04

I have PDF documents manually uploaded to firebase storage (dataset folder) and I'm trying download and retrieve them in reactjs, so far I'm able to download the urls and they're showing up in console but not sure why they're not displaying in the page. Please help fixing this.

import React from 'react';
import { storage } from "../config/firebase";
import { ref, listAll, getDownloadURL } from "firebase/storage"

function ForwardPE() {

const fetchImages = async () => {
  const storageRef = await ref(storage, "dataset");
  const result = await listAll(storageRef);

  const urlPromises = result.items.map((imageRef) => getDownloadURL(imageRef));

  return Promise.all(urlPromises);
};

const loadImages = async () => {
  const urls = await fetchImages();
  console.log(urls);
};

loadImages()
      
  return (
    <div className="file-grid">
      <div className="file-wrap">
        <h1>PDF FILES HERE</h1>
      </div>
  </div>
  );
};

export default ForwardPE;

Firebase.js

import { initializeApp } from "firebase/app";
import {getFirestore} from 'firebase/firestore'; 
import { getAuth } from "firebase/auth";
import { getAnalytics } from "firebase/analytics";
import { getStorage } from "firebase/storage";



const firebaseConfig = {
  apiKey: "AIzaSyAqW6kUwy4VGS8iBb72lXqK0v3ZnxR_Ohk",
  authDomain: "ai-web-app-1eba6.firebaseapp.com",
  projectId: "ai-web-app-1eba6",
  storageBucket: "ai-web-app-1eba6.appspot.com",
  messagingSenderId: "488293461041",
  appId: "1:488293461041:web:62aec35f6d5e09a0e63910"
};

const firebaseApp = initializeApp(firebaseConfig); 
export const projectFirestore = getFirestore();

export const storage = getStorage();
export const firebaseAuth = getAuth(firebaseApp);
export const firebaseAnalytics = getAnalytics(firebaseApp); 

CodePudding user response:

You shouldn't share your firebase config object publicly. Now we can all access your database. I'd recommend making a new project. But this might be the solution to your question. Just a simple useState

import React, { useState } from 'react';
import { storage } from "../config/firebase";
import { ref, listAll, getDownloadURL } from "firebase/storage"

function ForwardPE() {

const [urls, setUrls] = useState([]);

const fetchImages = async () => {
  const storageRef = await ref(storage, "dataset");
  const result = await listAll(storageRef);

  const urlPromises = result.items.map((imageRef) => getDownloadURL(imageRef));

  return Promise.all(urlPromises);
};

const loadImages = async () => {
  const _urls = await fetchImages();
  console.log(_urls);
  setUrls(_urls);
};

loadImages()
      
  return (
    <div className="file-grid">
      <div className="file-wrap">
        {urls.map((url, index) => (
          <h1 key={index}>{url}</h1>
        ))}
      </div>
  </div>
  );
};

export default ForwardPE;
  • Related