Francisco Molina
Francisco Molina

Reputation: 57

React JS is not changing state after event inside FileReader

I've been trying to assign as a state the contents of a .txt file uploaded locally via an input tag. I used File Reader, however although the content of the files is printed, the state is not changed according to React dev tools.

Here's the code:

handleFile = (file) => {
var fileReader = new FileReader()
fileReader.readAsText(file)
fileReader.onloadend = function (e) {
  var content = e.target.result
  console.log(content)
  this.setState={
    text: content
  }

}

The function handleFile is being called here:

<input type="file" accept='.txt' className="custom-file-input" id="customFile"
onChange={e => this.handleFile(e.target.files[0])} />

Thanks a lot

Upvotes: 2

Views: 193

Answers (2)

setState is a method, so to use it you should type something like:

this.setState({key:value})

but it wouldn't work, couse "this" in your code is link to fileReader - and you need React. Try to use arrow function to throw correct "this":

fileReader.onloadend = (e)=> {
var content = e.target.result
console.log(content)
this.setState({
  text: content
})
}

Upvotes: 2

MD10
MD10

Reputation: 1531

try this.setState({ text: content }) without the = also use arrow function because this is not recognized in regular functions

Upvotes: 0

Related Questions