0

Can't for the life of me figure this out. Every time setState() is called, the component is supposed to re-render, right? I have a series of print statements set up, and so I can see that my handler is being fired but render() is not. Please help me understand what is going wrong here!

Here are the important parts of my code:

My constructor:

  constructor(){
    super();
    this.state = {upvoted:false}
    this.handleFavorite = this.handleFavorite.bind(this);
  }

My handler:

  handleFavorite(event){
    event.preventDefault();

    console.log("handleFavorite fired");

    var query=location.pathname;
    query = query.split('/');
    var username1=query[2];
    var playlist=query[3];

    var vote = this.props.data.vote;

    var self = this;

    if (username1) {
      request
        .post('/api/endpoint')
        .end(function(err, res) {
              self.setState({upVoted: true});
              self.forceUpdate();
              console.log("status "+res.body.status);
      });
    }

  }

My handler call:

render() {
  return (
    <div onClick={this.handleFavorite}>stuff</div>
  );
}
Kaitlyn
  • 201
  • 3
  • 15
  • How can you tell the component is not re-rendering ? Did you put a log statement that's not called, or... ? Please share the render function that should be called and is not. – LoremIpsum Nov 17 '16 at 07:49

2 Answers2

0

setState should trigger render for you, there is no need to calling forceUpdate

also, setState is asynchronous so your forceUpdate will fire before state gets updated

pwolaq
  • 6,343
  • 19
  • 45
0

I just have the same thing with a different behaviour. I think you need to pass the reference of the function(handleFavorite) to onClick checkout this answer also: Why is my onClick being called on render? - React.js

Community
  • 1
  • 1
Sabrican Ozan
  • 738
  • 3
  • 9