4

I have a file object that I need to put into state. The reason why I am trying to do this is it was offered as a possible solution for re-rendering the DOM in order to clear a value out of FileReader(). Here is a link that this current thread is stemming from

Node 'crypto' SHA256 hashing model behaving erratically

I'll put a condensed react component here so you can see what's going on.

import React, { Component } from "react";

class SearchPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      files: []
    };
  }

  onChange(e) {
    let files = e.target.files;
    this.setState({ files: files[0] });
    console.log(files[0]);
    console.log(this.state.files)
  }

  render() {
    return (
        <div onSubmit={this.onFormSubmit}>
          <input type="file" name="file" onChange={e => this.onChange(e)} />
        </div>
    );
  }
}

export default SearchPage;

console.log(files[0]} gives something like this:

File(1) {name: "1.txt", lastModified: 1549429792266, lastModifiedDate: Tue Feb 05 2019 22:09:52 GMT-0700 (Mountain Standard Time), webkitRelativePath: "", size: 1, …}
lastModified: 1549429792266
lastModifiedDate: Tue Feb 05 2019 22:09:52 GMT-0700 (Mountain Standard Time) {}
name: "1.txt"
size: 1
type: "text/plain"
webkitRelativePath: ""

If I console.log(this.state.files) I get [].

I have set the initial state as "" and null to no avail. I eventually want to use the state for a FileReader() function.

Any ideas or solutions are appreciated. Thanks!

Hanley Soilsmith
  • 579
  • 2
  • 9
  • 27

2 Answers2

5

setState is an asyncronous function, you need to console log inside the callback function of setState which is executed once the state is updated.

onChange(e) {
  let files = e.target.files;
  this.setState({ files: files[0] }, () => { console.log(this.state.files) });
  console.log(files[0]);

}
Aaditya Thakkar
  • 1,750
  • 13
  • 13
0

Here Files[0] is an object and you store that object in an array if you just change state files type to an empty object and console the state variable in the render method i thing the value will update. here is an example:

this.state = {
  files: {}
};
render() {
  console.log(this.state.files)
  return (
  --- 
  );
}
Rajesh Bhartia
  • 690
  • 4
  • 10