34
loading...
This website collects cookies to deliver better user experience
npx create-react-app real-time-plotting
real-time-plotting
and install a few additional libraries we needcd real-time-plotting
npm install react-plotly.js plotly.js socket.io-client
npm start
socket.io-client
library. We also store our backend URL in an env file and declare it as REACT_APP_SOCKET_URL
import { io } from "socket.io-client";
const socketURL = process.env.REACT_APP_SOCKET_URL;
const socket = io(socketURL);
socket.on("connect",()=>{
socket.emit("ping_graph", {symbol: "ril.ns"});
});
graph-plot
(refer to server-side implementation if you want to know how this works)socket.on("graph_plot", res => {
let response = JSON.parse(res);
});
response
variable now.useState
is surprisingly easy to wrap your head around!useEffect
hook is used to run a particular function either after a complete render or when certain values get changed (by passing them in an array as a second argument)const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const socketURL = process.env.REACT_APP_SOCKET_URL;
const socket = io(socketURL);
socket.on("connect",()=>{
socket.emit("ping_graph", {symbol: "ril.ns"});
});
socket.on("graph_plot", res => {
if(loading===true){
setLoading(false);
}
let response = JSON.parse(res);
response.config = {responsive: true}
setData(response);
});
return () => socket.disconnect();
}, []);
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
loading
and data
where data is intially set to null
and loading is sent to true
graph_plot
, we do two important thingsif(loading===true){
setLoading(false);
}
setData(response);
if
statement that sets loading
state as false when it runs for the first timesetData
assigns the socket value we just got as the data
useEffect
.return () => socket.disconnect();
return (
<div className="wrapper">
<Plot
{...data}
/>
)}
</div>
)
Plot
component.loading
variable as the statement to a conditional operatorreturn (
<div className="wrapper">
{loading?(
<p>
loading
</p>
):(
<Plot
{...data}
/>
)}
</div>
)
Link to Github Repository
Cover Photo by Tech Daily on Unsplash