Reputation: 751
Can anyone let me know why the below code still get Object is possibly 'null'
error even though I already checked whether event is null or not?
const handleImageChange = (event: Event) => {
if (event) {
event.preventDefault();
const selectedFile = event.currentTarget.files[0]; // ERROR:Object is possibly 'null'!
if (selectedFile) {
setFieldValue("photo", selectedFile);
}
}
};
Upvotes: 1
Views: 281
Reputation: 121
You should introduce a null check before picking the file in index "0".
const handleImageChange = (event: Event) => {
...
const { currentTarget } = event;
if (currentTarget.files.length === 0) return
const selectedFile = event.currentTarget?.files[0];
...
}
};
Upvotes: 1