0

I have the following piece of code in my app:

  const [files, setFiles] = useState(null);


 const onHandleChange = useCallback((e) => {
    const fileReader = new FileReader();
    fileReader.readAsText(e.target.files[0], "UTF-8");
    fileReader.onload = e => {
      console.log("e.target.result", e.target.result);
      setFiles(e.target.result);
    };
    console.log(JSON.stringify(files));
  });

I then pass onHandleChange to a component that I import using:

<Sidebar onSave={onSave} onRestore={onRestore} onReset={onReset} setElements={setElements} removeElements = {removeElements} onDownload={onDownload} 
               onHandleChange={onHandleChange}/>

However, the JSON.stringify gives me a null. I'm not quite sure why. I know the file is read because the console.log shows me the JSON I uploaded.

1 Answer 1

2

React this.setState, and useState does not make changes directly to the state object.

React this.setState, and React.useState create queues for React core to update the state object of a React component.

So the process to update React state is asynchronous for performance reasons. That’s why changes don’t feel immediate.

For more help why react setstate usestate does not update immediately

function App() {
  const [files, setFiles] = useState(null);

  const onHandleChange = useCallback((e) => {
    const fileReader = new FileReader();
    fileReader.readAsText(e.target.files[0], "UTF-8");
    fileReader.onload = e => {
      setFiles(e.target.result);
    };
    console.log(JSON.stringify(files)); //you can't use the files state here
  });

  console.log(files, 'files'); //  here you will get console
  return (
    <div>
      <input type='file' onChange={(e) => onHandleChange(e)} />
    </div>
  );
}
export default App;
Sign up to request clarification or add additional context in comments.

3 Comments

But even if I move the console.log up a into the .onload function (right after setFiles) it still doesn't work. Or is it asynchronous even to that level? How would I change it if I wanted to wait?
Set files this variable in render method !
@user1357015 Upadate my answer pls check

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.