Home > Enterprise >  How do I run both getDownloadURL and getMetaData at once and get the results into the same object? F
How do I run both getDownloadURL and getMetaData at once and get the results into the same object? F

Time:09-02

So I have this component where it renders out medias (images or videos) to show what are the uploaded medias (to Firebase Storage). Currently I have a useEffect hook that pulls the data from Firebase Storage and stores the data into a state. How it looks like currently:

const [uploadedMedia, setUploadedMedia] = useState([]);

  useEffect(() => {
    const uploadedMediaRef = ref(storage, "appTutorials/"   data.id   "/");

    const getMedia = async () => {
      setUploadedMedia([]);
      listAll(uploadedMediaRef).then((resp) => {
        resp.items.forEach((item) => {
          getDownloadURL(item).then((url) => {
            setUploadedMedia((prev) => [...prev, url]);
          });
        });
      });
    };
    getMedia();
  }, []);

What's happening is that on initial render, the app will list all the data that are present in the storage, then we loop through the data to get the download URL through getDownloadURL method that is provided by Firebase. I then put the URL into the uploadedMedia state which is then a list which later I will map through to render the images/videos.

However, what I want to do is to get the metadata through getMetaData method, so that I can know what type of media is it rendering. This is so that I can do conditional rendering on images and videos where images should be rendered using <img> tag and and videos on <iframe> or <video> tag. I want to pull both URL and metadata at once so that I can store both response in an object as such:

[
    {
        url: "https://link-to-media-here",
        type: "png",
    }
]

How can I achieve this? I imagined it should be easy as we can just do array manipulation (?) but I just can't seem to get it so far.

CodePudding user response:

The API does not provide a way to combine the results of getDownloadURL and getMetaData. getDownloadURL is a bit special in that it potentially makes a change to object metadata to add a token string that provides access to the object via the returned URL. getMetaData simply fetches what's there and makes no changes. So you will have to call both in order to get everything you need. You could certainly invoke them both asynchronously and use their returned promises along with Promise.all to wait until they both complete.

  • Related