Update reaction state via Socket.io

The My React component uses data from socket.io as state.

I'm not sure how easy it is to update the state when the data is updated without reprocessing the entire component.

Sample 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')
);
+4
source share
1 answer

You can add a 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() {}
});
+5
source

Source: https://habr.com/ru/post/1617626/


All Articles