Reputation: 1356
I'm working on the React application.
I need to develop a dashboard in my application.
For that dashboard I need to show data in real-time.
I'm new to react, what is the correct way to do this?
Upvotes: 2
Views: 12200
Reputation: 72
I guess it's important to highlight that React is a library, not framework. And the domain of this library is a rendering (View).
What you're asking about is mostly about business logic and so called state management.
There're several ways how you can manage data in your web application.
The first layer is the connection layer - how you get data. Here you actually have two options long polling - periodically requesting endpoints and websockets. The first one is much more simple in implementation and suits well if you don't have too many clients to be updated immediately, the second one otherwise.
Next is how you manage state and update view. For simple application you can use React's API to handle this with useEffect hook https://reactjs.org/docs/hooks-effect.html#example-using-hooks-1 For something big it's better to investigate Redux + Redux-saga/RxJS or Mobx
Upvotes: 2
Reputation: 930
For real time data you can use HTTP polling, HTTP streaming, Server-sent events, web sockets. But efficient real time data is WebSockets. For react and node you can use https://www.npmjs.com/package/websocket package.
Here is a sample client code
import React, { Component } from 'react';
import { w3cwebsocket as W3CWebSocket } from "websocket";
const client = new W3CWebSocket('ws://127.0.0.1:8000');
class App extends Component {
componentWillMount() {
client.onopen = () => {
console.log('WebSocket Client Connected');
};
client.onmessage = (message) => {
console.log(message);
};
}
render() {
return (
<div>
Sample code for WebSockets.
</div>
);
}
}
export default App;
As soon as the request is accepted by the server, we will see WebSocket Client Connected on the browser console.
Upvotes: 2