2

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

1
  • tip: content = await file.text() Commented May 3, 2020 at 16:15

2 Answers 2

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 }) } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, didn't notice the error while calling setState, also thanks for explaining the context of this!
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.