Errors in socket.on Listeners Result in Inaccurate Progress and Index Matching for Multiple Video Uploads

Is there a way to make sure that the `socket.on('upload-progress')` listener accurately updates the upload progress for each video as multiple videos are uploaded simultaneously? Currently, it appears that the listener is updating the progress for all videos indiscriminately, regardless of their respective indexes. The provided `handleUploadLectureVideo` function manages the video uploads and progress updates:

async function handleUploadLectureVideo({ files }: any, index: number) {
  const file = files[0];
  const formData = new FormData();
  formData.append("file", file);
  formData.append("name", file.name);

  socket.emit("upload-file", {
    file,
    fileMeta: {
      originalName: file.name,
    },
    name: file.name,
  });

  console.log("index outside", index);

  // Setting video upload progress
  socket.on("upload-progress", function (data: number) {
    console.log("index", index);
    setValue(`courseLectures.${index}.uploadingProgress`, data);
  });

  // Setting video ID into payload after successful video upload
  socket.on("upload-success", function (data: any) {
    setValue(`courseLectures.${index}.lectureVideo`, data.id);
  });
}

The backend code (Nest JS) for uploading videos is as follows:

async handleFileUpload(@MessageBody() data: any, @ConnectedSocket() client: Socket) {
    const file = data.file;
    const meta = data.fileMeta;
    const name = data.name;
    const filename = this.getCompleteFileName(meta);
    const completePath = join('video-lectures', filename);

    await promises.writeFile(completePath, file);

    this.vimeoClient.upload(
      completePath,
      { name },
      async (uri: string) => {
        const video = new Video();
        video.url = uri;
        const result = await this.videoRepository.save(video);
        client.emit('upload-success', result);
      },
      (bytesUploaded: number, bytesTotal: number) => {
        const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2);
        client.emit('upload-progress', percentage);
      },
      error => {
        console.log('Failed because: ' + error);
        client.emit('upload-failed', error);
      },
    );
  }

It has been observed that the index value within the `socket.on('upload-progress')` and `socket.on('upload-success')` listeners does not align correctly with the video being uploaded, resulting in inaccurate progress and video IDs being assigned to the wrong videos. How can this code be adjusted to ensure that the correct video progress and IDs are associated with the corresponding videos during simultaneous uploads?

An attempt was made to simultaneously upload multiple videos using the `handleUploadLectureVideo` function provided, but discrepancies were noticed in progress updates and video ID assignments. Specifically, the `index` value within the `socket.on('upload-progress')` and `socket.on('upload-success')` listeners did not match the expected video index, leading to progress and IDs being allocated incorrectly.

It was anticipated that the `index` value passed to the `handleUploadLectureVideo` function would be accurately captured within the `socket.on` listeners, ensuring that progress and ID updates for each video would be linked to the correct index.

Answer №1

It seems like the event "upload-progress" should trigger each time a video makes progress. One suggestion is to define generic socket listeners outside of this function with a wider scope, and then use their payload to update the upload progress of the corresponding video by specifying something like {videoId: "xxx"} or index. Another option could be to dynamically include the ID/Index in the event name string and register it within your function using

socket.on('progress-upload-${index}')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of the Toastr "options" seems to be malfunctioning

I am having some trouble with my Toastr notification messages. While the message does display, I seem to be unable to make use of any options that I set. Despite specifying some options, they do not seem to work as intended. $('#editButton').c ...

Attempting to navigate through nested data within existing mapped data

The data set 1 consists of an array that contains another array called data set 2. Currently, data set 1 is being mapped to display a single-column table with data1.name inside it. The data1.name serves as a clickable button that reveals the related data i ...

Creating unique appbars for different sections on my sidebar in ReactJs

I am trying to implement a responsive drawer and AppBar using material-ui (@material-ui/core). My goal is to display a specific AppBar for each section of the drawer. For instance, when the user navigates to the Timetable section, I want the AppBar label t ...

What is the best method for disabling autoscroll for a specific div id when the :target attribute

I created this accordion menu using only html and css, but the buttons are built with the :target id. Is there a way to prevent the automatic scrolling when any button is clicked without using javascript? It currently moves to the anchor #id. I've se ...

Set the minimum date for the jQuery datepicker

Having trouble with jQuery datepickers for selecting from and to dates? Currently, the code restricts the selection in the second datepicker to dates after the one selected in the first datepicker. However, what if you need to set the to datepicker to allo ...

"RecognitionAudio variable missing" and "InactiveRpcError occurred" [Utilizing the Google text-to-speech API]

I have a goal I'd like to achieve. A user communicates with a web browser. The web browser records the user's voice as a WAV file using Recorder.js and sends it to a server running on Google App Engine Standard environment with Python 3.7. The ...

Guide to transforming a JSON file value into a JavaScript list

I need assistance with converting a string of comma-separated values in a JSON file into a list. The goal is to iterate through the list in a for loop and click on each element. Can you help me with this task? testdata.json : {"optionsList":&quo ...

Having trouble retrieving the HTML content after deploying my application on Heroku

I encountered an issue with my index.js file in Express Node.js once I deployed the app on Heroku. In production, I'm getting an error that seems to indicate that the server is unable to find my index.html file. *-src ---index.html ---index.js * ...

Setting the state for an element in React after it has been mounted - a step-by-step guide

My React application features a user data form with a notification message that appears after submitting the form. The notification can be either a success or fail message, with the latter potentially containing multiple error types. I handle the error typ ...

Learn how to implement JavaScript code that allows a video to start playing only upon clicking a specific button

Within the confines of a div lies a <video autoplay> <source src='myvid'> </video>. This div initially has a display ='none' setting in its CSS. Upon receiving a click event, the display property changes from none to b ...

What is the process for removing an item from a JSON file using an HTTP DELETE request in a Node.js environment?

Essentially, I have a JSON file containing user and group data and I need to delete a specific group from it. Below is a snippet of the JSON file named authdata.json: [{ "name": "Allan", "role": ["Group Admin", "Super Admin"], "group": ["Cool- ...

Switching ng-Idle countdown time from seconds to minutes is possible by adjusting the configuration settings

I have implemented ng-idle in my application, where the warning popup appears after 10 seconds with the message: "Your session will be close in 10 seconds" However, I need to change this to minutes. The session should be closed in 5 minutes instead. How ...

When incorporating `io.sockets.emit` within the router, what happens if the socket connection has not been fully established beforehand?

Utilizing io.sockets.emit in the router as shown below: db.SomeModel.find({}, function(err, modelDate) { io.sockets.emit('eventName', modelData); } ); If a socket takes around 10 seconds to be established (just an example), a ...

I am having trouble programmatically setting the 'checked' attribute for a newly added checkbox on an asp.net page

I dynamically added checkboxes using jQuery on my ASPX page and attempted to check some checkboxes by default based on conditions. However, I encountered the following error: Uncaught TypeError: undefined is not a function I tried the following methods ...

Switch up the autofill hue for Stripe checkout using NextJS

We are implementing Stripe's Element payment feature with NextJS. We have extracted and utilized only the relevant part related to element payments from this link. In order to change the background color when filling in the credit card number using a ...

What steps need to be taken to utilize the fast-json package within a web browser environment?

In my quest to enhance the performance of my apps, I stumbled upon two intriguing packages. Currently, I am working on a forum-style app that constantly receives and processes information from APIs. Despite optimizing my frontend JavaScript to the best of ...

Exploring the intricacies of mapping an Array of Arrays

I'm currently tackling a data manipulation project that involves iterating through an array of arrays and generating a single string containing all possible combinations found within these arrays. For instance: const array = [ [{id: 1}, {id: 2}], ...

Unexpected output from nested loop implementation

Having some arrays, I am now trying to iterate through all tab names and exclude the values present in the exclusion list. json1 ={ "sku Brand": "abc", "strngth": "ALL", "area ...

Ways to display an SVG spinner prior to a substantial UI refresh

I am currently facing an issue with updating 10 apexcharts bar charts simultaneously in a Vue app. When this process occurs, it takes approximately one second to load completely, and during that time, I would like to display an svg spinner. However, the co ...

Tips for documenting curried functions using Js docs

I'm encountering issues while trying to use Js docs for generating static documentation of my project. When attempting to run the js doc command, I am faced with numerous parse errors specifically in areas where I have curried functions. Strangely, my ...