Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update React state via Socket.io

My React component uses data from socket.io as it's state.

I am unsure how to just update the state when the data is updated without re-rendering the entire component.

Example code.

var socket = io();

var data = {
  components: [{key: '',name: '',markup: ''}]
};


socket.on('data', function(_) {
  data = _;
});

var Components = React.createClass({
  displayName: "Components",

  getInitialState: function getInitialState() {
    return data;
  },

  handleChange: function handleChange() {
    this.setState(data);
  },

  render: function render() {
    /* render */
  }
});

ReactDOM.render(
  React.createElement(Components, {
    data: data
  }),
  document.getElementById('main')
);
like image 844
Brian Douglas Avatar asked Nov 26 '15 14:11

Brian Douglas


1 Answers

You can add socket event listener to componentDidMount, like this

var socket = io();

var data = {
  components: [{key: '',name: '',markup: ''}]
};

var Components = React.createClass({
  displayName: "Components",

  componentDidMount: function () {
    socket.on('data', this.handleData);
  },

  componentWillUnmount: function () {
    socket.removeListener('data', this.handleData);
  },

  handleData: function (data) {
     this.setState(data);
  }, 

  getInitialState: function () {
    return data;
  },

  handleChange: function handleChange() {
    this.setState(data);
  },

  render: function render() {}
});
like image 189
Oleksandr T. Avatar answered Sep 22 '22 06:09

Oleksandr T.