score:1

Accepted answer

typo in:

const [parsedFile, setParsedFile] = useState(null);

file reader code:

const fileReader = new FileReader();

fileReader.readAsText(e.dataTransfer.files[0]);

fileReader.onload = () => {
  setParsedFile(fileReader.result);
};

score:1

You are trying to print parsedFile, but in the state is it called parsedFiled. You are also printing the value before the onload callback sets the state. Try moving the print into the callback function.

The onload callback function is asyncronous, so you can't use the value immediately after invoking it because there is no guarantee that the function has resolved. In order to use the file contents, you can do one of the following: Place the relevant code in the render function so it can react to the state change; write code and insert it into the callback function so that it is called when the contents are available; use a syncronous read function or wrap the asyncronous function in a promise, so that you can have an expectation about how it resolves (e.g. await the promise and use the contents immediately after).


Related Query

More Query from same tag