Retrieve information from reader.readAsArrayBuffer

I'm facing an issue with the following code. My goal is to return the uploadData array back to the hello variable, but it's returning as a blank array. Even though the console log shows the correct array of data like {name: 'bob'}, it becomes blank after the reader.readAsArrayBuffer line. Any insights on why this might be happening?

Hello = validateSpreadsheet(file, rows)

validateSpreadsheet = function (fileUpload, templateRows) {
  let uploadData = [];
  for (const file of fileUpload.files) {
    const fileExtension = file.name.split(".").pop();
    let valid = false;
    if (fileExtension === "csv") {
      valid = true;
    }
    if (!valid) {
      throw "Unsupported file type, file must be 'of type .csv";
    }
    const reader = new FileReader();

reader.onload = async (e) => {
  const data = new Uint8Array(e.target.result);

  const workbook = XLSX.read(data, {
    type: "array",
    cellDates: true,
    dateNF: "dd/mm/yyyy",
  });
  if (workbook.SheetNames.length === 0) {
    console.error("No sheets");
  }
  for (const sheetName of workbook.SheetNames) {
    const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {
      defval: null,
    });

    for (let row of rows) {
      uploadData.push(row);
    }
  }
  console.log(uploadData);
};
   reader.readAsArrayBuffer(file);
    return uploadData;
  }
};

Answer №1

uploadData will only be updated once the reader.onload function is executed, as it runs asynchronously. To work around this issue, you can provide a callback function to validateSpreadsheet that will receive the accurate uploadData.

validateSpreadsheet(file, rows, function (uploadData) {
  // perform actions on the data here
  console.log(uploadData);
});

validateSpreadsheet = function (fileUpload, templateRows, callback) {
  let uploadData = [];
  for (const file of fileUpload.files) {
    const fileExtension = file.name.split(".").pop();
    let valid = false;
    if (fileExtension === "csv") {
      valid = true;
    }
    if (!valid) {
      throw "Unsupported file type, file must be 'of type .csv";
    }
    const reader = new FileReader();

    reader.onload = async (e) => {
      const data = new Uint8Array(e.target.result);

      const workbook = XLSX.read(data, {
        type: "array",
        cellDates: true,
        dateNF: "dd/mm/yyyy",
      });
      if (workbook.SheetNames.length === 0) {
        console.error("No sheets");
      }
      for (const sheetName of workbook.SheetNames) {
        const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {
          defval: null,
        });

        for (let row of rows) {
          uploadData.push(row);
        }
      }
      console.log(uploadData);
      callback(uploadData);       // pass the correct `uploadData` to your callback function here
    };
    reader.readAsArrayBuffer(file);
    return uploadData;
  }
};

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

Unable to send an array from a PHP function back to an AJAX request

In my javascript file, I have an ajax request to fetch data from foo.php, which returns an array of mysql results. Here is the code snippet: //foo.js $(document).ready(function(){ $.ajax({ url:"foo.php", type:"POST", ...

Unending cycle in React with a custom hook

After attempting to create a method using a custom react hook to streamline state logic across multiple components, I encountered an invariant violation labeled "prevent infinite loop". function useCounter(initial) { const [count, setCounter] = useState ...

Error loading resource: The server returned a 404 status code indicating the requested resource was not found in the Node.js socket.io

My challenge involves setting up a server with Node.js and socket.io which starts perfectly fine. However, when I attempt to access my server's site through the browser, it shows "Cannot Get /" and in the console, an error appears saying "Failed to Lo ...

"Troubleshooting: Fixing the issue with jQuery datepicker not

After implementing the jQuery Datepicker on a field, I noticed that even though assigning a value to the field shows in Chrome's developer tools... https://i.sstatic.net/We7Ua.png Unfortunately, the assigned value does not show on the front end. I ...

Warning: UnsupportedRepoVersionError: The repository versions are not compatible. Please check the version of IPFS-JS (0.55.3) and Node.js (14.17.0) being used

Recently, I delved into the world of ipfs js and currently have version 0.55.3 installed (https://www.npmjs.com/package/ipfs). Alongside, my setup includes node js version 14.17.0 (LTS) on MacOS BigSur 11.4. However, while following a tutorial at https:// ...

Replacing a string using Regular Expression based on certain conditions

When working with a node.js server, I encountered the need to modify URL addresses using JavaScript in a specific way: For instance: hostX/blah/dir1/name/id.js?a=b --> name.hostY/dir2.js?guid=id&a=b Another example: hostZ/dir1/name/id.js --> ...

I keep encountering errors with TypeGuard

Looking for some guidance with typescript. Even after implementing a type guard (and including the '?' symbol), I'm still encountering errors in the code snippet below. Is the syntax correct or should I make changes to the tsconfig file? int ...

"Resetting count feature in AngularJS: A step-by-step guide

I have a list consisting of four items, each with its own counter. Whenever we click on an item, the count increases. I am looking to reset the counter value back to zero for all items except the one that was clicked. You can view the demonstration here. ...

Tips for displaying consecutive information from a Sequelize query with associations in Node.js

Attempting to create a straightforward sequential output from a demo Node.js app and Sequelize has proven to be challenging for me. I'm struggling to comprehend how promises and Bluebird can assist me in achieving the desired result: User: John Doe ...

Retrieve the property called "post" using Restangular

With the following code, I am fetching a list of 'postrows': $scope.postrows = {}; Restangular.all('/postrows').getList().then(function(data){ $scope.postrows = data; }); The returned JSON structure is as follows: { id: 1, post ...

Issue encountered while attempting to load several google charts simultaneously

What do I need? I am in need of two Google charts, one on each tab of the website as shown in the screenshot below: Tabs What seems to be the issue? The second chart is not loading properly and showing mixed information. This can be observed in the scre ...

Why is "this" not undefined even though I did not bind it in my function's constructor?

When I click my button, it triggers the onClick function below: <button onClick={() => this.onDismiss(item.objectID)} type="button" > The onDismiss function filters a list and updates my React application. Interestingly, I didn't bind th ...

Is it feasible to trigger a cloud function upon reading a specific document in Firebase?

Within my Firebase realtime database, there exists a document labeled /queue containing multiple children. I am looking to trigger a cloud function whenever this particular /queue is retrieved. While I have already configured cloud functions for onCreate ...

What is the best way to handle an ajax call while working with the main Vue instance?

I have a VueJS component that makes an AJAX call to GitHub using the following code: (Child) Component Vue.http.get('user/repos').then((response) => { console.log(response); }, (response) => { console.log(response); }); The issue ...

Using setInterval in conjunction with an ajax request will automatically trigger the closing of the DateTimePicker

Looking for a solution to my issue: setInterval(function(){ $.ajax({ url: "{{ route('logout_checker')}}", type: "GET", success: function(data){ ...

The following middleware is not functioning properly on a local SSL server

When I run my Nextjs app without SSL using "next dev", the middleware functions as expected without any errors. However, if I attempt to run the app with SSL enabled, an empty middleware function triggers an error. The code for the middleware function (l ...

Oops! We encountered an issue trying to find the "list" view in the views directory

Here are the images I have: This is the code for my app.js file And this is the code for list.ejs located in the views directory Unfortunately, my index.html file is empty. Below is the full error log: Error: Failed to lookup view "list" in the views di ...

Effective management and structuring of ExpressJS routes

I recently made the switch from PHP to NodeJS and Express, and I must say, it has been quite a learning experience. Following online tutorials to build web apps with Express has been eye-opening. I decided to tackle a project using just JavaScript, but I ...

Tutorial on packaging javascript with Parcel for Electron apps

I am currently utilizing Parcel with Electron by leveraging the resources provided at https://github.com/parro-it/electron-parcel-example. The specific project I am working on can be found at https://github.com/patrykkalinowski/dcs-frontlines-electron My ...

Importing a CSV file from the web (Google Sheets) and converting it into a JavaScript array

I am working with a Google spreadsheet ( https://docs.google.com/spreadsheet/ccc?key=0Agymc2_-gI59dGxvRnZoRzNuNENIUE9kZ0h6WExxSXc&usp=sharing ) where I store my golf scores after each round. My goal is to import this data into my JavaScript file and ...