简体   繁体   中英

React useState - file Reader is not updated

I use the following code in order to get the values from an file upload (which is XML). But the console output is always undefined.

Would someone point me to my mistakes?

My JS code:

export default function XYZ() {
     ...
     const [xmlUpload, setXmlUpload] = useState(null);

    function uploadXMLHandler(e) {
        setXmlUpload(e.target.files[0]);
    }

    useEffect(() => {
        if (xmlUpload != null) {
            var convert = require('xml-js');
            var fileReader = new FileReader();
            var result =  fileReader.readAsText(xmlUpload);   
            console.log(result);
        }
    });


...

my HTML Code is

  <div className="uploadXML">
            <input type="file" onChange={uploadXMLHandler} />
        </div>

You're using the FileReader wrong. FileReader#readAsText does not immediately return the result, it starts reading asynchronously. It will fire the load event when it's done. So you should be listening to that event, like so:

var fileReader = new FileReader();
fileReader.onload = () => console.log(fileReader.result);
var result =  fileReader.readAsText(xmlUpload);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM