user1357015
user1357015

Reputation: 11696

using file reader state in reactjs

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.

Upvotes: 0

Views: 1822

Answers (1)

Mayur Vaghasiya
Mayur Vaghasiya

Reputation: 1482

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;

Upvotes: 2

Related Questions