'Javascript file upload e.target == null when choosing another file after initially chose one

I've currently implemented the file uploading using <input> and for some reason when I try to change the file after already chosen the file. The website will crash stating the even.target is null.

<Button label="Upload S3 File">
  <input type="file" onInput={(e) => handleFileUpload(e)} />
</Button>

And here's my handler function, to be exact, the error happens on

file: e.target.files ? e.target.files[0] : null,

// Set up the handler
const [formValues, setFormValues] = useState<RequestData>({
  overrideUbi: "",
  marketplace: "",
  isTier1: "",
  brandName: "",
  brandURL: "",
  file: null
});

const handleFormChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  const { name, value } = event.target;
  // console.log(event);
  setFormValues((prevState) => ({
    ...prevState,
    [name]: value,
  }));
};

const handleFileUpload = (e: any) => {
  console.log("upload");
  console.log(e.target)
  console.log(e.target.files)
  if (!e.target.files) return;
  setFormValues((prevFormValues) => ({
    ...prevFormValues,
    file: e.target.files ? e.target.files[0] : null,
  }));
};

Not sure why it states e.target is null if I choose another file after have one file chosen already. My if statement for checking e.target == null also doesn't work preventing the website from crashing. Thanks!

Update: I've attached a couple of screenshot showing the exact error.

Warning Messages

e.target is null

One interesting finding is that if I use e.persist(), I can change the file I want to upload without triggering this error. I don't know why exactly that is, if someone can explain what is going on in this lifecycle I would truly appreciate it. Thanks!



Solution 1:[1]

try e.currentTarget.files, if you have a reference set on the input component.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MK4