Richard
Richard

Reputation: 165

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>

Upvotes: 0

Views: 1044

Answers (1)

IceMetalPunk
IceMetalPunk

Reputation: 5566

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);

Upvotes: 1

Related Questions