How to re render table component upon receiving a notification from web socket in React JS?

大憨熊 提交于 2021-01-27 17:43:26

问题


Im using React table and loading a page which displays a table with data fetched from an API. Im also listening on a web socket and right now, whenever something is sent over a web socket, Im printing a console message. Now I want to reload the table(in turn making the API call) when I receive any update on the web socket.

    class TableExp extends React.Component {
    constructor() {
    super();

this.state = {
  tableData: [
    {
      resourceID: '',
      resourceType: '',
      tenantName: '',
      dealerID: '',
      status: '',
      logFilePath: '',
      supportPerson: '',
      lastUpdatedTime: '',
    },
  ],
  //testMessage: [{ message: 'Initial Message' }],
};
}

    componentDidMount() {
this.websocket = new WebSocket(socket);

this.websocket.onopen = () => {
  axios.get('https://myapi.com', {
    headers: {},
    responseType: 'json',
  })
  .then((response) => {
    this.setState({ tableData: response.data });
  });
  console.log('Socket Opened');
};

this.websocket.onmessage = (event) => {
    const data = (JSON.parse(event.data));
    const status = data.status;
    console.log(data.status);
    this.forceUpdate();

  if (status === 'failed') {
      console.log('Error message received');
      this.reloadTable();
    }
};

this.websocket.onclose = () => {
  this.statusDispatcher('closed');
};
}

 reloadTable() {
  this.forceUpdate();
}

render() {
  const { tableData } = this.state;

return (
  <ReactTable
      data={tableData}
      noDataText="Loading.."
      columns={[
        {
          columns: [
            {
              Header: 'Dealer ID',
              accessor: 'dealerId',
              id: "dealerId",
            },
            {
              Header: 'Location',
              id: "dealerId",
            },
          {
          columns: [
            {
              filterable: false,
              Header: 'File Path',
              accessor: 'logFilePath',
            },
             {
              filterable: false,
              Header: 'Date',
              accessor: 'Date',
            },
          ],
        },
      ]}
      defaultPageSize={20}
      style={{
        height: '450px', // This will force the table body to overflow and scroll, since there is not enough room
      }}
      className="-striped -highlight"
  />
);
}

回答1:


You can simple setState within onmessage

this.websocket.onmessage = (event) => {
  let data = [];
  const status = data.status;

  if (status === 'failed') {
    console.log('Error message received');
    // And do nothing, or empty table
  } else {
    data = JSON.parse(event.data);
  }
  
  this.setState({ tableData: data });
};


来源:https://stackoverflow.com/questions/46056865/how-to-re-render-table-component-upon-receiving-a-notification-from-web-socket-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!