0

At the moment I render my component inside a .erb file like this:

<%= react_component('Counter', number: @counter) %>

This component has a function that uses promised-xhr:

push: function(operation) {

    if(operation) {
      new_number = this.state.number +1;
    } else {
      new_number = this.state.number -1;
    }

 // This call works.
 // this.setState({number: new_number})

     XHR.post("/update", {
      data: {
        count: new_number
      }
    }).then(function(response) {
   // XHR.post is successful, so I can log the response.
      console.log(response.body.number);
   // But setState does not work because of 'this'
      this.setState({number: reponse.body.number})
    })

}

this.setState({number: response.body.number)} does not work because this is no longer the component. I am planning to use React.findDOMNode(this.refs.myComponent) to find my component and trigger the new state.

However, I can't figure how to use the react_component to assign a ref to my Counter component.

Hannes Johansson
  • 1,794
  • 2
  • 15
  • 28
Matias Faure
  • 822
  • 1
  • 9
  • 20

1 Answers1

1

How about memoizing this, then using a local variable inside the callback?

push: function(operation) {
  // ... 
  // Store `this` as local variable `_this`:
  var _this = this 

  XHR.post("/update", {/*...*/})
    .then(function(response) {
    // use local variable `_this`, which still refers to the component:
      _this.setState({number: reponse.body.number
    })
}

As a side note, ref might not help. After calling getDOMNode, you'd have a DOM node (browser built-in), not a React component.

rmosolgo
  • 1,854
  • 1
  • 18
  • 23
  • You are right. Promises are not good for what I am trying to do, old style callbacks neither. I am left wondering how to implement a component that changes state after receiving data from a request. – Matias Faure Jul 17 '15 at 11:36
  • 1
    Use the `setState` function in the request handler, as shown above. Assign the component to `_this` (a local variable) so that can reference it from the request handler. – rmosolgo Jul 17 '15 at 21:11