Unable to select uploaded files for tagging in React
P粉312631645
2023-08-15 20:43:24
<p>I'm using React to create a file upload. I want the status variable to be set to the uploaded file (.docx or .pdf) as soon as the file is uploaded. But when calling set state, it shows up as undefined. </p>
<pre class="brush:php;toolbar:false;">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)
}
}
}</pre>
<p>Once <code>setSelectedFile(file)</code> occurs, it shows <code>selectedFile</code> as undefined. Is this a specific reason why it happened? </p>
This is because when you call or log it in the console, your status has not been updated. You can log your status in the
useEffect
hook to view it when updated. Here is an example:I think your code works as expected, but when you try to call it, the state hasn't been updated yet.
According to React official documentation:
Now, this is my guess, but you can try adding this code: