I have a component called linechart which takes rpm(speed) and time as input.This speed is actually a machine's speed which is comming through websocket whenever it changes.This rpm(speed)value and it's related time also stored in a db.At first I fetch 20 value of rpm(speed) and it's related time and store it in an array to drow the line.Now if any data comes through the websocket i pop one value of speed from the array and push changed value in the array.Thats how the line chart update. Most of the time the machine remain at same speed so websocket doesn't send any value and my chart remain steady respect to time.But at the same the machine is still running at same speed or become off. Now,my requirment is update the chart continuouly if the machine runnig at 35 rpm 10rpm or 0rpm and remain in same speed.I want to pass the machine current state info to my chart so that it can update with time.
I have tried to send the same props with now time to the line chart from it's parent component(tranding) using setTimeout and setInterval but i think it's not the right approach.
This is the parent component of line chart
import React from "react";
import { Link, useLocation } from "react-router-dom";
import PieChart from "./pichart";
import BarChart from "./Barchart";
import Linechart from "./Linechart";
import "./Tranding.css";
import { MdAnalytics } from "react-icons/md";
import Example from "./line";
import config from "./config";
export default class Tranding extends React.Component {
constructor(props) {
super(props);
this.state = {
id: this.props.machine.machineNo,
rpm: null,
update_at: null,
efficiency: 0,
loss: 100,
shift_efficiency: 0,
shift_loss: 100,
loading: false
};
}
//This function will be called immediate after first render.
componentDidMount() {
//initial data fetching for pie charts.
this.daily_efficiency_fetcher("daily");
this.shift_efficiency_fetcher("Shift A");
setTimeout(() => {
setInterval(() => {
var today = new Date();
this.setState({
id: this.state.id,
rpm: this.state.rpm,
time: today.toISOString()
})
}, 1500)
}, 2000);
}
//Fetching data for shift efficiency pie chart depending on user selection.
getShiftEfficiency(e) {
var user_selected_option = e.target.value;
this.shift_efficiency_fetcher(user_selected_option);
}
//Fetching data for daily efficiency pie chart depending on user selection.
getDailyEfficiency(e) {
// console.log(e.target.value);
// console.log(this.state.id);
var user_selected_option = e.target.value;
this.daily_efficiency_fetcher(user_selected_option);
}
//It's a fetcher function which takes an arguments as input and fetch data depending on it's input.
daily_efficiency_fetcher(selected_option) {
var user_selected_option = selected_option
console.log(user_selected_option)
fetch("http://" + config.api + ":8000/api/dailyefficiency/", {
method: "POST",
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: this.state.id,
selected_option: user_selected_option
})
})
.then((response) => response.json())
.then((data) => {
console.log(data)
var data_size = Object.keys(data).length
console.log(data_size)
//calculating the efficiency and loss
if (data_size != 0) {
var machine_efficiency = (Math.floor(data.runtime) / ((Math.floor(data.total_hours) * 3600) - Math.floor(data.offline))) * 100
console.log(machine_efficiency.toFixed(2))
var machine_loss = 100 - machine_efficiency
console.log(machine_loss.toFixed(2))
this.setState({
efficiency: machine_efficiency.toFixed(2),
loss: machine_loss.toFixed(2),
loading: false
})
}
else {
this.setState({
efficiency: 0,
loss: 100,
loading: false
})
}
})
}
//It's a fetcher function which takes an arguments as input and fetch data depending on it's input.
shift_efficiency_fetcher(selected_option) {
var user_selected_option = selected_option
fetch("http://" + config.api + ":8000/api/shiftefficiency/", {
method: "POST",
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: this.state.id,
selected_option: user_selected_option
})
})
.then((response) => response.json())
.then((data) => {
console.log(data)
var data_size = Object.keys(data).length
//calculating the efficiency and loss
if (data_size != 0) {
var machine_efficiency_of_selected_shift = (Math.floor(data.runtime) / ((Math.floor(data.total_hours) * 3600) - Math.floor(data.offline))) * 100
console.log(machine_efficiency_of_selected_shift.toFixed(2))
var machine_loss_of_selected_shift = 100 - machine_efficiency_of_selected_shift
console.log(machine_loss_of_selected_shift.toFixed(2))
this.setState({
shift_efficiency: machine_efficiency_of_selected_shift.toFixed(2),
shift_loss: machine_loss_of_selected_shift.toFixed(2),
loading: false
})
}
})
}
render() {
// console.log(this.props.location.state)
console.log(this.props.machine.rpm)
console.log(this.state.efficiency)
//destructure the object
const { id, trendValue } = this.state
if (this.state.loading) {
return <p>Loading Loading ...</p>;
}
return (
<div id="tranding">
<div className="text-right" id="trendtitle">
<div className="" id="trending_heading">
<h4>Machine {this.state.id} Trending</h4>
</div>
<div id="reportlink">
<Link to={"/machine" + this.state.id + "/report"}>
<button
type="button"
id="reportbutton"
className="btn btn-outline-secondary font-weight-normal"
>
<MdAnalytics size={22} />
Report
</button>
</Link>
</div>
</div>
<div id="chart_container">
<div className="line" id="linechart">
<Linechart id={this.state.id} rpm={this.props.machine.rpm} updateAt={this.props.machine.update_at} />
</div>
<div className="bar" id="barchart">
<BarChart id={id} rpm={this.props.machine.rpm} />
</div>
<div className="pie_current" id="piechart">
<div className="dropdown " id="shiftpiechart">
<select
id="shiftselect"
className="btn btn-outline-secondary"
onChange={this.getShiftEfficiency.bind(this)}
>
<option value="Shift A" selected>Shift A</option>
<option value="Shift B">
Shift B
</option>
<option value="Shift C">Shift C</option>
</select>
</div>
<div className="pi">
<PieChart
efficiency={[this.state.shift_efficiency, this.state.shift_loss]}
/>
</div>
</div>
<div className="pie_monthly" id="piemonthly">
<div className="buttongroups" id="buttongroup">
<select
id="shiftselect"
className="btn btn-outline-secondary"
onChange={(e) => this.getDailyEfficiency(e)}
>
<option value="daily" selected>Daily</option>
<option value="weekly" >
Weekly
</option>
<option value="monthly">Monthly</option>
</select>
</div>
<div className="pi">
<PieChart efficiency={[this.state.efficiency, this.state.loss]} />
</div>
</div>
</div>
</div>
);
}
}
And this is the line chart component
import React from "react";
import { Line } from "react-chartjs-2";
import "./Linechart.css";
import config from "./config";
import { MdContentCopy } from "react-icons/md";
export default class Linechart extends React.Component {
constructor(props) {
super(props);
this.state = {
id: this.props.id,
rpm: [],
time: [],
loading: false
};
}
componentDidMount() {
this.getLineChartValues(this.state.id)
}
getLineChartValues(id) {
fetch("http://" + config.api + ":8000/api/linechart/" + id)
.then((response) => response.json())
.then((data) => {
var time = []
var rpm = []
console.log(data)
console.log(data[0].time.slice(11, 16))
for (var i = 0; i < data.length; i++) {
rpm.push(data[i]["rpm"])
time.push(data[i]["time"].slice(11, 16))
}
this.setState({
rpm: rpm.reverse(),
time: time.reverse(),
loading: false
})
});
}
render() {
const { rpm, time } = this.state;
console.log(this.props.rpm)
console.log(time)
if (this.props.rpm != null) {
time.reverse();
rpm.reverse();
time.pop();
time.reverse();
rpm.pop();
rpm.reverse();
time.push(this.props.updateAt.slice(11, 16));
rpm.push(this.props.rpm)
}
if (this.state.loading) {
return <p>Loading Loading ...</p>;
}
return (
<div className="linewrapper">
<Line
height="22vh"
width="100%"
type="line"
data={{
labels: time,
datasets: [
{
label: "Current Shift RPM",
backgroundColor: "#E1E5EA",
borderColor: "#A7BBC7",
pointBackgroundColor: "#A7BBC7",
pointBorderColor: "#fff",
data: rpm,
fill: false,
tension: 0.6
},
],
}}
options={{
responsive: true,
plugins: {
title: {
display: true,
text: "RPM Line Chart",
},
legend: {
display: false,
labels: {
color: "rgb(255, 99, 132)",
},
},
},
scales: {
y:
{
min: 0,
max: 50,
stepSize: 5,
},
x:
{
},
}
}}
/>
</div>
);
}
}