TypeError: Invalid attempt to spread non-iterable instance and Synthetic Events

Tags: , , , ,

I am trying to build a csv file uploader using react. I am getting the “Invalid attempt to spread non-iterable instances” error when the file is selected and I try to set the state with it. This is my code that gives that error:

const IFImport = (props) => {
    const [file, setFile] = useState(null);
    const [loading, setLoading] = useState(false);

  const onUpload = async (e) => {
     const csvFile = e;
     setFile(...file, csvFile)

  return (
          <Link to={"/"}>
            <Button color="link">&lt;</Button>
          Upload Enrollment Information
          <ErrorList error={props.error} />
      <Label>Upload a CSV File for Enrollment</Label>
    {file !== null ? <p>{file.name}</p> : ""}
                onChange={e => onUpload(e)}
              />{" "}

export default IFImport;

I assumed this was an issue with setting the state here in this onUpload function so I tried no setting the state here but then I just get a synthetic even error. Can anyone tell me the best way to handle this sort of upload?


First of all you are trying to spread null value which will obviously fail (that’s the initial value for file in state).

Secondly – e isn’t the file you are looking for, it’s the Event object. If you want to get the uploaded files, use

const csvFile = e.target.files;

instead, which will hold every file uploaded by user as an array.

Source: stackoverflow