Snowflake Snowflake - 1 month ago 7
React JSX Question

React adding value to button from callback

render: function(){
var id = 2;

return(
<div>
<input type="text" ref="id" value={id} />
</div>
)
}


I know that I can add a value to a button using a variable (as above), however I am getting my initial value from a mysql database, which requires a callback function. I was using socket.io to try and get the value:

render: function(){
socket.emit('get_value')
socket.on('returned_value', function (value) {
//does not work
id = value
}

return(
<div>
<input type="text" ref="id" value={id} />
</div>
)
}


The emit works, but socket.on does not. I have also tried to wrap the render in the socket.io method to force it to wait, but it obviously does not work. I have no idea how to get the value from the app.js class to index.js dynamically.

In app.js:

socket.on('get_value', function () {
mysql.getCurrentValue('*', function (result) {
socket.emit('returned_value', result)
});
});


Trying to include the mysql script directly in index.js (ie mysql = require('mysql.js')) also causes the page not to render, but I dont know why. I works from app.js which is why im using socket.io.

Answer

I've put together a quick example. Put the socket code in the componentDidMount() method and set the id as state (this.setState({ id: id });. Then set the value of the input to this.state.id.

  componentDidMount() {
    socket.emit('get_value')
    socket.on('returned_value',  function (value) {
      this.setState({id: id});
    }.bind(this); // think you have to bind, didn't test
  }
  render() {
    return(
      <input type="text" ref="id" value={this.state.id} />
    );
  }