Justin
Justin

Reputation: 3039

access component `this` from container

I'm using props to pass in functions that my component needs to run. Keeping the component as dumb as possible. Instead of putting into the functions into the react class.

I need to update my component state, but I'm having trouble accessing setState from within my prop function. I've tried doing something like, so my function can access it, but I keep getting an error:

Component

  componentDidMount(){
    this.props.loadImage(this.props.src).bind(this);
  }

Container Load Image Function

let loadImage = (src)=>{
  console.log('loading Image');    
  fetch(src).then(function( data ) {
      console.log('success');
      that.setState({'imgUrl':src});
  }).catch(function( error ) {
      console.log('fail');
      setTimeout(loadImage(src), 1000);
  });

};

Error:

component.js:67 Uncaught TypeError: Cannot read property 'bind' of undefined(…)
  1. Why is bind undefined on this prop function?
  2. Am I just approaching this the wrong way?

Thanks!

Upvotes: 0

Views: 129

Answers (2)

Fabian Schultz
Fabian Schultz

Reputation: 18546

Why bind this in the first place?

class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      data: ''
    }
  }
  componentDidMount() {
    this.doSomething('hello');
  }
  doSomething(data) {
    this.setState({
      data
    }, () => console.log(this.state));
  }
  render() {
    return(
      <div>{this.state.data}</div> 
    );
  }

}

ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>

Upvotes: 1

Rami Enbashi
Rami Enbashi

Reputation: 3556

If loadImage doesn't return a function then you are probably calling bind on undefined. You might want to do this.props.loadImage.bind(this, this.props.src); instead.

Upvotes: 1

Related Questions