2

I have two function

  1. convertToBase64(file) for converting file
  2. addData(values) for sending the converted file. But result in the second function is always undefined. How to fix this?
async function convertToBase64(file) {
  const fileReader = new FileReader();
  fileReader.onload = () => {
    const srcData = fileReader.result;
    console.log('scrData: ', srcData);     // result is correct
    return srcData;
  };
  fileReader.readAsDataURL(file);
}

async function addData(values) {
  const converted = await convertToBase64(values.file);
  console.log(converted);       // result undefined
  await addDoc(collection(db, 'list'), {
    image: converted,
  });
}

I have tried try...catch, async-await function, but I can't find a solution anyway

XMehdi01
  • 5,538
  • 2
  • 10
  • 34
gkj5g4wh4g
  • 31
  • 3

1 Answers1

4

The convertToBase64() function doesn't return a value explicitly, so the code you provided always returns undefined. You can change the function such that it returns a Promise that resolves once the FileReader has done reading the file in base64 successfully, And take care of any rejections or errors occurs:

const imgFileInput = document.getElementById("img");
imgFileInput.addEventListener("change", addData);

function convertToBase64(file) {
  return new Promise((resolve) => {
    const fileReader = new FileReader();
    fileReader.onload = () => {
      const srcData = fileReader.result;
      resolve(srcData);
    };
    fileReader.onerror = (error) => {
      reject(error);
    };
    fileReader.readAsDataURL(file);
  });
}

async function addData() {
  try {
    const imgFile = imgFileInput.files[0];
    const converted = await convertToBase64(imgFile);
    console.log(converted);
  } catch (error) {
    console.error("Error while converting to Base64:", error);
  }
}
<input type="file" id="img" />
XMehdi01
  • 5,538
  • 2
  • 10
  • 34