reactjs - Handling continuous stream of logs using socket-io in react
问题描述
I am relatively new to sockets, I am working on a react project where user should be able to see the logs during the deployment kinda like the Jenkins build logs. I can't share the exact code but the code looks more or less like the below code.
import socketIOClient from 'socket.io-client';
class ShowLog extends Component{
constructor(props) {
super(props);
this.state = {
stateLogs: []
};
this.socketLogs = [];
}
// Ignoring the componentDidMount and other unnecessary stuff
// this function will establish the socketio connection
streamLog = (socketId, url) => {
this.clientSocket = socketIOClient(url);
this.clientSocket.on('connect', () => {
this.clientSocket.emit('join', socketId);
});
this.clientSocket.on('data', this.handleLogs);
// error handling here
}
handleLogs = (data) {
if(data.length){ // I will be getting messages as an array of strings
this.socketLogs.push(...data);
this.setLogs(this.socketLogs); // calling another method to update state
}
}
// used throttle with 100ms to create jenkins like log instead of pushing them all at once.
setLogs = throttle((data) => {
this.setState({ stateLogs: data });
}, 100);
render() {
const { stateLogs } = this.state;
return (
<>
// other logic here.
{
stateLogs.map(message => <li key={message}>{message}</li>)
}
</>
)
}
}
In my case I will be getting at least 10 messages each second. Also I am using throttle to reduce number of renders for smooth flow of logs.
The problem here is that when the backend is pushing the logs, the logs are getting updated after 2-5 seconds from front end.
Can anyone please give your suggestions on improving the code to reduce the delay that I have mentioned above.
解决方案
推荐阅读
- amazon-web-services - 将元数据添加到 S3 对象,同时保留现有的元数据和 ACL
- ios - Flutter - 从 Firebase 加载此个人资料图片时遇到问题
- maven - 已部署的 Github 包中缺少父 POM
- python - 循环遍历excel工作表并使用Python将值存储在变量中
- c# - 使用 moq - void 方法的单元测试 c#
- r - 香农多样性的箱线图
- maven - 在 Maven 命令行参数中传递占位符变量
- ansible - Ansible Jinja2 循环问题
- database - 抛出异常:System.Data.dll 中的“System.Data.OleDb.OleDbException”
- excel - VBA代码列下的超链接特定单元格