1

I'm using a library for working with the content of files. I'm using the function instead of arrow function because I need to access the decode method. But then I want to set the result of a function to a state of the component. But of course, in that case, this is not pointing to the component anymore.

I'm not sure what to do there?

reader.loadFile(file)
                    .then((response) =>  {
                        reader.iterateLines({
                            eachLine: function (raw, progress, lineNumber)  {
                                console.log(this.decode(raw))
                                this.setState({
                                    txtFileContent: this.decode(raw)
                                });
                            },
                        })
                    })
                    .catch( (reason): void => {
                        console.log(this);
                    });
Person
  • 2,190
  • 7
  • 30
  • 58
  • 2
    Outside the function, assign `this` to a different variable and reference that instead. See [How to access the correct `this` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Felix Kling Nov 19 '19 at 13:31

4 Answers4

1

assign this to that while you are still capable:

const that = this;

Later, inside the scope where this is no longer the 'this' you wanted, so you can still call it's methods.

that.setState(....);

Remember, 'that' is a generic proposal, any semantic name for this constant will a better option.

Edorka
  • 1,781
  • 12
  • 24
0

If possible, use functional react component with useState hook, and get rid of context problems! https://reactjs.org/docs/hooks-intro.html

Rafael Hovsepyan
  • 781
  • 8
  • 14
0

When creating the function that you want to use as a callback, bind this to it, as such:

eachLine: (function (raw, progress, lineNumber)  {
    console.log(this.decode(raw))
    this.setState({
        txtFileContent: this.decode(raw)
    });
}).bind(this),
Dmitri Farkov
  • 9,133
  • 1
  • 29
  • 45
-1

Try binding this

this.setState.bind(this, { txtFileContent: this.decode(raw) })
tony
  • 1,274
  • 1
  • 11
  • 27
  • 1
    How/where/when should this be applied? `.bind` returns a new function. – Felix Kling Nov 19 '19 at 13:33
  • Given the second argument you pass to `.bind`, this proposal makes no sense. `this` cannot refer to two different values at the same time, but that's what your proposal is implying (since you are referring to `this.decode` and `this.setState` which live on different objects, as per OP's problem description). – Felix Kling Nov 19 '19 at 13:35
  • would do const update = this.setState.bind(this); and then calling update(newState) ? – Edorka Nov 19 '19 at 13:36
  • This can be solution with this approach. In outer scope we can define setState function `const setState = this.setState.bind(this)`; – Rafael Hovsepyan Nov 19 '19 at 13:56