Auto Binding in React / ES6

I was working on a project for my web design course in late 2017, a website for newbie investors to track and learn about cryptocurrencies.  I developed the site in React, so I had to use Javascript ES6 syntax.  I have a method in my App component that would read in the current price of a few cryptos and display them on the home page (www.cryptotracker.pro).  At first I used the normal definition below for my updateData() method:

updateData() {
   console.log('updateData funtion called')
   axios.get('https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,IOT&tsyms=USD')
   .then(res => {
     const cryptos = res.data;
     console.log(cryptos);
     this.setState({ cryptos: cryptos })
   })
}

I called this method on componentDidMount(), and it worked fine. I also added an “update” button on the form to run updateData() again.  Even though the button called the same updateData() method from inside the same App class, I kept getting an error.

Finally, I figured out that the following would make the button work:

<button onClick={this.updateData.bind(this)}>Update Data</button>

After my “this.updateData”, I had to add .bind(this).  It seems like if I define the method within a class, the method would be automatically bound to “this” of the class. But it doesn’t work that way, so I had to bind upData() to “this” by adding “.bind(this).

However, then one of the TAs in my bootcamp showed me the workaround — *autobinding*.  I love that word; it sounds cool for some reason.  I just used a fat arrow function when I created the method and it automatically bound it to the class.  I only had to change the first line to “updateData = () => {“….

  updateData = () => {
    console.log('updateData funtion called')
    axios.get('https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,IOT&tsyms=USD')
      .then(res => {
        const cryptos = res.data;
        console.log(cryptos);
        this.setState({ cryptos: cryptos })
      })
  }

After this change, I could call the update and leave out the “.bind(this).”

<button onClick={this.updateData)}>Update Data</button>

This is a good article on ES6 autobinding: https://www.ian-thomas.net/autobinding-react-and-es6-classes/.

I deployed the client side-only version of CryptoTracker here (www.cryptotracker.pro).  In the development environment, we had Google Oauth working with a MongoDB so people could login and store cryptos that they want to track (out of a list of over 2,000). We had trouble deploying the back-end technology. We are still working on that.  Please check it out.

CryptoTracker: www.cryptotracker.pro

Github: https://github.com/jbhafner/react-crypto

Leave a Reply

Your email address will not be published. Required fields are marked *