Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am using React Native with RxJS and up until now, whenever I subscribe to an observable I have been doing:

observable.subscribe(() => {
     this.setState({ loading: true });
}.bind(this));

But since I upgraded to React Native 0.16.0, everywhere I have performed bind(this) on an inline function declared with the ES2015 arrow notation, React Native picks it up as an error. However when I change the arrow notation back to ES5 regular function notation as below:

observable.subscribe(function() => {
    this.setState({ loading: true });
}.bind(this));

The errors seem to go away.

What is going on here?

What are you trying to bind this? That seems like something you would have to do only if you are not using an arrow function? – azium Jan 25, 2016 at 16:32 .. I ageed with @azium. If you write ()=>{} then this from the outer scope is already bound in the function. – Ben Clayton Feb 20, 2016 at 19:18

When you use an arrow function you're already binding this to that particular function. So:

() => {} === function() {}.bind(this)

Related to your question, I would recommend also checking out FrintJS, which comes with React and React Native integration too: https://github.com/frintjs/frint-react-native

It ships with an observe higher order component, which allows you to stream props to your component using an RxJS observable, so your base component is always written as a stateless function.

Example:

import React from 'react';
import { Observable } from 'rxjs';
import { observe } from 'frint-react';
function MyComponent(props) {
  return <p>Interval: {props.interval}</p>;
export default observe(function () {
  // return an Observable emitting a props-compatible object here
  return Observable.interval(1000)
    .map(x => ({ interval: x }));
})(MyComponent);

More on this topic:

  • FrintJS on GitHub
  • Streaming props to React component
  • observe higher-order component
  • Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.