Home  >  Q&A  >  body text

Unable to select uploaded files for tagging in React

<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>
P粉312631645P粉312631645403 days ago405

reply all(2)I'll reply

  • P粉523335026

    P粉5233350262023-08-16 14:23:10

    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:

    useEffect(() => {
        console.log("文件 >> ", selectedFile);
      }, [selectedFile]);

    reply
    0
  • P粉760675452

    P粉7606754522023-08-16 14:11:16

    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:

    set函数只会更新下一次渲染的状态变量。
    如果在调用set函数之后读取状态变量,你仍然会得到在调用之前屏幕上的旧值。

    Now, this is my guess, but you can try adding this code:

    setSelectedFile(file)
    
    setTimeout(() => {
        console.log(selectedFile); 
    }, 5000);

    reply
    0
  • Cancelreply