2

I have a class that looks something like this

export class TestScreen extends Component<any, LoginScreenState> {
  private wallet: Wallet;

  async connect() {
    this.wallet = WAL.accessContext.initWallet(getWalletProviders()[0]);
    ....
  }

render() {
    return (
        <div>
            <button onClick={this.connect}>Connect</button>
            <br />
        </div>
    );
    }
}

I get the following error

Unhandled Rejection (TypeError): Cannot set property 'wallet' of undefined

I understand that error, but I'm not sure what the correct pattern to use here is. I only want to set that value value when connect() is run.

I don't want to initialize the object to some garbage and then replace it ether. Feel like I'm missing something obvious here.

Antoine Boisier-Michaud
  • 1,575
  • 2
  • 16
  • 30
Warrick FitzGerald
  • 2,455
  • 3
  • 23
  • 31
  • 2
    How are you invoking `connect`? Do you have an instance of the class that you're using it with? – Silvio Mayolo Mar 16 '19 at 21:54
  • 1
    I think Silvio is on to something here, the message suggests that "this" is undefined which usually means that the function has been called from another context. If you change the async connect() { ... } to async connect = () => { ... } (which binds to the context of the class) it might work. But more information is needed here to be sure. – Felix Novovic Mar 16 '19 at 22:01
  • Thanks guys, I updated the code to show how I'm calling connect. I have a button which is on the render() output. – Warrick FitzGerald Mar 16 '19 at 22:04
  • Maybe try doing `onClick={() => this.connect()}` instead of `onClick={this.connect}`. I think it should fix your context problem. – Antoine Boisier-Michaud Mar 16 '19 at 22:08
  • 2
    Ahh yes, thank you, that is exactly the problem. – Warrick FitzGerald Mar 16 '19 at 22:40

1 Answers1

4

The this can be quite tricky in TypeScript. The this behaviour actually comes from JavaScript, as @ecraig12345 pointed out in the comments. When passing a reference of a method, there are some cases where you lose the context. This answer provides a great explanation. You can also learn more about that in the TypeScript documentation.

In your case, I suggest you do the following. It's a pretty common syntax.

onClick={e => this.connect(e)}
Antoine Boisier-Michaud
  • 1,575
  • 2
  • 16
  • 30
  • 1
    Just as a note, you can make the type checker catch problems like this with an explicit `this` signature on the function (`async connect(this: TestScreen)`). You can find more about how Typescript handles `this` on [the website](https://www.typescriptlang.org/docs/handbook/functions.html#this). – Silvio Mayolo Mar 16 '19 at 22:51
  • 1
    One clarification, the behavior of `this` is actually a part of JavaScript, not TypeScript. (but also affects TS since it compiles down to JS) – ecraig12345 Mar 17 '19 at 07:40