1

Here I simply want to call a walletconnect function when I click on the button. but it is not calling any function. please correct me if I'm wrong somewhere.

App.tsx

import * as React from 'react';
import WalletConnect from "@walletconnect/client";
import QRCodeModal from "@walletconnect/qrcode-modal";


class App extends React.Component<any, any> {

  constructor(props:any) {
    super(props)
    this.state = {
      address: ''

    }
    
    const connector = new WalletConnect({
      bridge: "https://bridge.walletconnect.org", // Required
      qrcodeModal: QRCodeModal,
    });
  }

  walletConnectFunc = async () => {
    const connector = new WalletConnect({
      bridge: "https://bridge.walletconnect.org", // Required
      qrcodeModal: QRCodeModal,
    });
    if (connector.connected) {
      alert("already connected")
      return
    }
    connector.createSession();
    connector.on("connect", async (error, payload) => {
      console.log("connect")
      if (error) {
        throw error;
      }

      // Get provided accounts and chainId
      const { accounts, chainId } = payload.params[0];
      console.log("connect account", accounts)
      console.log("chainid account", chainId)

      const obj = {
        "address": accounts[0],

      }
      this.setState({ address: obj.address })
      console.log(this.state.address)
      alert(this.state.address)
    })


  }
  render() {
    return (
      <div className="App">
          <div>
            <button className="btn btn-primary my-4" type="button" onClick={() => this.walletConnectFunc()}>WalletConnect</button>
          </div>
      </div>
    );
  }
}

export default App;

If more code is required then tell me in a comment section. I will update my question with that information.

7
  • 1
    Are you seeing any errors? What happens when you click the button? And btw onClick{(() => this.something()} can be changed to onClick={this.something} to avoid creating an extra function in the render. Commented Jan 14, 2021 at 1:01
  • 1
    Also is there a reason that method is async when you're not awaiting anything in it? Commented Jan 14, 2021 at 1:02
  • Same goes for the callback to onnector.onasync is for when you have things you want to await rather than using Promise .then syntax, you don't need to throw asyncs on functions otherwise. Commented Jan 14, 2021 at 1:18
  • @ZacAnger can you filter out my code coz i'm new with typescript and its literally my first app.tsx. i dont have such strong grip on ts concepts Commented Jan 14, 2021 at 1:23
  • I just want to call that walletconnect function , you can add an other function as well just for testing. in case something wrong with walletconnect package Commented Jan 14, 2021 at 1:25

2 Answers 2

3

Firstly, you should remove the redundant async keyword, Just walletConnectFunc() is enough. Simply because, inside your function do not call any await keyword, So that does not make sense.

Secondly, You just listen to event onClick like onClick={this.walletConnectFunc} to avoid creating an extra function in the render (As @Zac Anger's recommendation)

Finally, in case you have to access this inside the function, use arrow function or you can also bind this context like this way (For me, I highly recommend using the third way for the performance aspect)

In short, Just need to use arrow function when using context. enter image description here

import React, { Component } from "react";
import "./styles.css";

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {
      address: ""
    };

    this.walletConnectFuncAsync = this.walletConnectFuncAsync.bind(this);
  }

  async walletConnectFuncAsync() {
    await this.sleep(1000);
  }

  sleep(ms) {
    return new Promise((resolve) => {
      setTimeout(() => alert("Woke up after " + ms + "ms"), ms);
    });
  }

  walletConnectFunc() {
    alert(123);
  }

  render() {
    return (
      <div className="App">
        <div>
          <button
            className="btn btn-primary my-4"
            type="button"
            onClick={this.walletConnectFunc}
          >
            WalletConnect
          </button>
          <button
            className="btn btn-primary my-4"
            type="button"
            onClick={this.walletConnectFuncAsync}
          >
            WalletConnect_Async
          </button>
        </div>
      </div>
    );
  }
}

Demo on Codesandbox here

Sign up to request clarification or add additional context in comments.

1 Comment

functions are calling perfectly but the inner code is not working . Inner code which you can see for address and qrcode functions and walletconnect bridge
1

I guess what your are missing here is to bind the class method. You only have to write the binding method on the constructor like this:

...
  constructor(props:any) {
    super(props)
    this.state = {
      address: ''
    }
   this.walletConnectFunc = this.walletConnectFunc.bind(this);
...

4 Comments

Doesn't using the arrow function automatically do this ?
Correct @LeonBoehmer.
Nice! I'll keep the answer to share this knowledge. Thank, guys!
@Gust Check my answer with a more detailed explanation about arrow function vs this context :D

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.