Search code examples
reactjsasynchronousasync-awaitdropzonereact-dropzone

How to use Async Await in "onDrop" of "react-dropzone" ? (Parsing error: Can not use keyword 'await' outside an Async function)


I'm using "react-dropzone" for dropping files :

import React from "react";
import { useDropzone } from "react-dropzone";

const DropzoneUpload = ({ onDrop, accept }) => {
  // Initializing useDropzone hooks with options
  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept
  });


  return (
    <div {...getRootProps()}>
      <input className="dropzone-input" {...getInputProps()} />
      <div className="text-center">
        {isDragActive ? (
          <p className="dropzone-content">Release to drop the files here</p>
        ) : (
          <p className="dropzone-content">
            Drag 'n' drop some files here, or click to select files
          </p>
        )}
      </div>
    </div>
  );
};

export default DropzoneUpload;

And it's used in App.js like this :

<DropzoneUpload
        onDrop={onDrop}
        accept={
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        }
      />

Where the onDrop function is :

const onDrop = useCallback(async acceptedFiles => {
    // this callback will be called after files get dropped, we will get the acceptedFiles. If you want, you can even access the rejected files too
    console.log(acceptedFiles);
    const axiosInstance = axios.create({
      baseURL: "http://localhost:5000"
    });

    const reader = new FileReader();
    reader.onabort = () => console.log("file reading was aborted");
    reader.onerror = () => console.log("file reading has failed");
    reader.onload = () => {
      // Do whatever you want with the file contents
      const binaryStr = reader.result;
      const body = JSON.stringify({
        binaryStr
      });
      await axiosInstance.post("/api/upload", body);
    };

    acceptedFiles.forEach(file => reader.readAsArrayBuffer(file));
  }, []);

The problem : when I add Async Await to the callback function onDrop I get : Parsing error: Can not use keyword 'await' outside an Async function

So how can I wait to the answer from the server ?


Solution

  • // you forgot add async keyword here 
    reader.onload = async () => {
      const binaryStr = reader.result;
      const body = JSON.stringify({
        binaryStr
      });
      await axiosInstance.post("/api/upload", body);
    };
    

    Also you can delete top level async at useCallback(async....