I am creating a file upload using react. I want to set the state variable to the uploaded file(.docx or .pdf) as soon as the it was uploaded. But when the set state calls, it shows undefined.
const [selectedFile, setSelectedFile] = useState(null)
<Input type="file" onChange={handleImageUpload} accept={config.type}/>
const handleImageUpload = (event: { target: { files: any[] } }) => {
const file = event.target.files[0]
if (file) {
if (file.size > config?.fileSize) {
setErrorMessage(config.fileSizeError)
} else if (file?.name.endsWith(config.type)) {
setSelectedFile(file)
} else {
reader.readAsDataURL(file)
}
}
}
As soon as the setSelectedFile(file)
happens, it shows selectedFile
is undefined. Is there a specific reason why this is happening ?
3
Answers
I think, your code works as expected, but it’s just your state hasn’t get updated when you tried to call it.
From the react official docs:
Now, this is my speculation, but you can try to add this code:
I tried to change
event
type to be aPartial
instance ofChangeEvent
:and also changed
onChange
to accept the changeevent
and pass it tohandleImageUpload
It works properly and you can view
selectedFile
using auseEffect
hook.This is happening because your state hasn’t updated when you called or logged it in the console. You can log your state in a
useEffect
hook to see it when it updates. Here’s an example;