Overcoming Asynchronous Hurdles in a File Sharing Web App

Building a file-sharing web app presents its unique set of challenges, and one of the hurdles we faced was grappling with asynchronous behavior during file uploads. In this blog post, we’ll delve into the issue we encountered and the solution that propelled our file-sharing app forward.

The Challenge

In the process of developing our file-sharing web app using React.js and Firebase Storage, we noticed a snag in the user experience — after users uploaded their files, the anticipated redirection to the preview page wasn’t happening. A closer look at the code revealed that the culprit was the asynchronous nature of the file upload process.

Investigating the Issue

Understanding the intricacies of asynchronous operations in JavaScript is crucial when dealing with tasks like file uploads. We discovered that the redirection logic was getting triggered before the upload had completed, causing an incomplete user experience.

The Solution

To address this issue, we restructured our uploadFile function to ensure that the saveInfo function, responsible for updating the database and triggering the redirection, would only be invoked after the upload task had successfully completed.

const uploadFile = async (file) => {
  try {
    const metadata = { contentType: file.type };
    const storageRef = ref(getStorage(app), 'file-upload/' + file?.name);
    const uploadTask = uploadBytesResumable(storageRef, file, metadata);

    uploadTask.on('state_changed', snapshot => {
      const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
      setProgress(progress);
    }, error => {
      console.error('Error uploading file:', error.message);
    }, async () => {
      // Upload completed successfully
      try {
        const downloadURL = await getDownloadURL(uploadTask.snapshot.ref);
        saveInfo(file, downloadURL);
      } catch (error) {
        console.error('Error getting download URL:', error.message);
      }
    });

  } catch (error) {
    console.error('Error uploading file:', error.message);
  }
};

This adjustment ensured a seamless experience for our users, as the redirection would now only occur once the file had been successfully uploaded.

Conclusion

Navigating the complexities of asynchronous operations is a common challenge in web development. Our experience with overcoming this hurdle in our file-sharing app reinforced the importance of meticulous code examination and the satisfaction of finding and implementing effective solutions.

As you embark on your own development journey, embrace these challenges, experiment with solutions, and celebrate the victories when they come!

github link: https://github.com/Blackie360/ShareHub

Happy coding!