Skip to content
Advertisement

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

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;
     console.log(csvFile)
     setFile(...file, csvFile)
  }

  return (
    <>
      <ContentRow>
        <h1>
          <Link to={"/"}>
            <Button color="link">&lt;</Button>
          </Link>
          Upload Enrollment Information
          <ErrorList error={props.error} />
        </h1>
      </ContentRow>
      <ContentRow>
      <Label>Upload a CSV File for Enrollment</Label>
          <FormGroup>
            <div>
    {file !== null ? <p>{file.name}</p> : ""}
            </div>
            <div>
              <Input
                type="file"
                name="data.file"
                multiple={false}
                onChange={e => onUpload(e)}
                accept="/csv"
              />{" "}
            </div>
          </FormGroup>
      </ContentRow>
    </>
  );
};

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement