I'm using ReactJS as a javascript library and I am getting the data in componentDidMount()
using axios
. These received data must be taken again every 60 seconds. What is the most efficient and good way to do this?
componentDidMount() {
const newGteeChartSeries = [];
const newGteeChartCategories = [];
const newmultiSelectOption = [];
axios.get(`http://www.xxxxxxx:xxxx/api/groupdata`).then(res => {
this.state.gteeChartSeries.map(() => {
const data = [];
res.data.map((item, index) => {
data.push(item.gtee);
newGteeChartCategories.push(item.isyeri);
newmultiSelectOption.push({ id: item.id, isyeri: item.isyeri });
});
newGteeChartSeries.push({ name: "GTEE", data });
});
this.setState({
teeTableData: res.data,
gteeChartSeries: newGteeChartSeries,
multiSelectOptions: newmultiSelectOption,
gteeChartoptions: {
...this.state.options,
xaxis: {
categories: newGteeChartCategories
}
}
});
});
}
One way of going about it is to move the data fetching logic to a separate method and create an interval that will invoke this method every 60 seconds.
Make sure you store the number returned from setInterval
on the component instance so you can use clearInterval
in componentWillUnmount
.
Example
class MyComponent extends React.Component {
interval = null;
componentDidMount() {
this.interval = setInterval(this.getData, 60000);
this.getData();
}
componentWillUnmount() {
clearInterval(this.interval);
}
getData = () => {
const newGteeChartSeries = [];
const newGteeChartCategories = [];
const newmultiSelectOption = [];
axios.get(`http://www.xxxxxxx:xxxx/api/groupdata`).then(res => {
this.state.gteeChartSeries.forEach(() => {
const data = [];
res.data.forEach((item, index) => {
data.push(item.gtee);
newGteeChartCategories.push(item.isyeri);
newmultiSelectOption.push({ id: item.id, isyeri: item.isyeri });
});
newGteeChartSeries.push({ name: "GTEE", data });
});
this.setState({
teeTableData: res.data,
gteeChartSeries: newGteeChartSeries,
multiSelectOptions: newmultiSelectOption,
gteeChartoptions: {
...this.state.options,
xaxis: {
categories: newGteeChartCategories
}
}
});
});
};
}
I would suggest abstracting the api request into its own function
componentDidMount(){
setInterval(yourApiCallFn(),60000)
}
You can wrap all in a function.
Call that function in ComponentDidMount()
, and use setInterval(myFunction(), 60000)
to call that function every 60 seconds
Below works without syntax error.Call that function without parenthesis
``componentDidMount() {
this.interval = setInterval( this.props.Details, 6000);
this.props.Details()
}
componentWillUnmount() {
clearInterval(this.interval);
}``
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With