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 ?
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:
the set function only updates the state variable for the next render.
If you read the state variable after calling the set function, you will
still get the old value that was on the screen before your call.
Now, this is my speculation, but you can try to add this code:
setSelectedFile(file)
setTimeout(() => {
console.log(selectedFile);
}, 5000);