Search code examples
javascriptreader

Return data from reader.readAsArrayBuffer


I have the following code. I am trying to return the uploadData array back to the hello variable. However it is returning as a blank array. The console log prints out the correct array of data, like this: {name: 'bob'}, but after the reader.readAsArrayBuffer line, it becomes blank. Does anyone know why?

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;
  }
};

Solution

  • uploadData isn't updated until your reader.onload function is called (it is called asynchronously). So, to get around this, you can pass a callback function to validateSpreadsheet that receives the correct uploadData.

    validateSpreadsheet(file, rows, function (uploadData) {
      // do something with 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);        // the correct `uploadData` will be passed to your callback here
        };
        reader.readAsArrayBuffer(file);
        return uploadData;
      }
    };