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.

5
  • 2
    How are you invoking connect? Do you have an instance of the class that you're using it with? Commented Mar 16, 2019 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. Commented Mar 16, 2019 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. Commented Mar 16, 2019 at 22:04
  • Maybe try doing onClick={() => this.connect()} instead of onClick={this.connect}. I think it should fix your context problem. Commented Mar 16, 2019 at 22:08
  • 2
    Ahh yes, thank you, that is exactly the problem. Commented Mar 16, 2019 at 22:40

1 Answer 1

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

2 Comments

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.
One clarification, the behavior of this is actually a part of JavaScript, not TypeScript. (but also affects TS since it compiles down to JS)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.