Introduction to Firebase Storage - Part 2

Retrieving & deleting files

Introduction to Firebase Storage - Part 2

Retrieving & deleting files


About the author

Victoria Lo is a full-stack web/software developer from Markham, Ontario, Canada. In addition to software development, she teaches various development techniques to engineers worldwide in over 100 published technical guides reaching over 50,000 readers a month. Her work has been featured in The Startup, Level Up Coding, Better Programming, and JavaScript in Plain English.

Be sure to follow Victoria on her website, GitHub, and Twitter.


images/introduction-to-firebase-storage-part-2.png

In this article, we shall continue from where we left off in the previous article on How to Upload Files to Firebase Cloud Storage.

It covers how to retrieve and delete files from Firebase Cloud Storage.

Retrieve files from Firebase

Refer to the previous article to learn how to set up Firebase Cloud Storage and create our project that we will continue building in this article.

Step 1: Create allImages state

Initialize an array called allImages. This array will hold all the image URLs retrieved from Firebase.

 const [allImages, setImages] = useState([]);

Step 2: getFromFirebase

Next, create a function called getFromFirebase that will handle retrieving all files from Firebase.

The goals of the function are to:

  1. Get reference to the storage bucket
  2. Use listAll() to get all the reference object inside it

listAll() returns the reference to the images, not the images themselves. It has 2 properties: items and prefixes. Items are the image reference whereas prefixes are folders, in case you have nested folders in storage.

Below is an example of what listAll() returns when I have 8 images in storage.

images/listAll-firebase.png

  1. Then loop through each items reference with forEach() to obtain the image URL with getDownloadURL()
  2. Finally, add this URL into the allImages array with setImages()
  const getFromFirebase = () => {
    //1.
    let storageRef = storage.ref();
    //2.
    storageRef.listAll().then(function (res) {
        //3.
        res.items.forEach((imageRef) => {
          imageRef.getDownloadURL().then((url) => {
              //4.
              setImages((allImages) => [...allImages, url]);
          });
        });
      })
      .catch(function (error) {
        console.log(error);
      });
  };

Step 3: Display images

We can then create a component where we can display our images from the URLs in the allImages array.

 <div id="photos">
     {allImages.map((image) => {
        return (
           <div key={image} className="image">
              <img src={image} alt="" />
              <button onClick={() => deleteFromFirebase(image)}>
               Delete
              </button>
           </div>
         );
     })}
</div>

On each image, we can have a Delete button to allow users to delete the picture they clicked on. Here’s how to implement deletedFromFirebase() for the button.

Delete files from Firebase

Step 4: deleteFromFirebase

The deleteFromFirebase function takes the image URL as an argument and deletes that URL from Firebase.

Here’s how to implement the function:

  1. Using refFromURL(), get the image reference from Firebase Storage of the image that should be deleted.
  2. Then use .delete() to delete the image from Firebase.
  3. Finally, remove that URL from the allImages array.
const deleteFromFirebase = (url) => {
    //1.
    let pictureRef = storage.refFromURL(url);
   //2.
    pictureRef.delete()
      .then(() => {
        //3.
        setImages(allImages.filter((image) => image !== url));
        alert("Picture is deleted successfully!");
      })
      .catch((err) => {
        console.log(err);
      });
  };

The result

images/how-to-delete-files-from-firebase-cloud-storage.gif

And that’s how to upload images, retrieve and display them, and delete them!

To view the project I made for this tutorial, please visit the repo here. And be sure to read the Firebase Documentation for more information.

I hope it’s been helpful in getting started with using Firebase Cloud Storage. Cheers!


Be sure to follow Victoria on her website, GitHub, and Twitter for more great development guides and resources.

Also be sure to check out Setting Up Firebase in an iOS App


About PullRequest

HackerOne PullRequest is a platform for code review, built for teams of all sizes. We have a network of expert engineers enhanced by AI, to help you ship secure code, faster.

Learn more about PullRequest

Victoria Lo headshot
by Victoria Lo

October 28, 2020