Reputation: 283
I am new to react and not sure whether this question should be asked or not. Have searched many blogs but could not come to a conclusion. I have a rest API which is updating data continuously at server side, take for example stock data API. Now, if I use $.get
of jquery or fetch()
from react library it will update data only on initial page load. What I am looking for is as data change occurs from the API end simultaneously the change should be reflected in the user interface. Any help will be appreciated.
As discussed with @Shubham Khatri please find te code below for react.
var StockData = React.createClass({
getInitialState: function() {
return {
stock: []
};
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (data) {
console.log(" Data value :"+data);
var old = data.replace("//", "");
this.setState({
stock: JSON.parse(old)
});
}.bind(this));
console.log(" Data value after bind :"+this.state.stock);
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
console.log(" Stock value :"+this.state.stock);
return (
React.createElement("div",null,
React.createElement("ul",null,
this.state.stock.map(function (listValue){
return React.createElement("li",null,listValue.t," ( ",listValue.e," ) - "," Current Price :",listValue.l_cur," Date : ",listValue.lt
);
})
)
)
);
}
});
Upvotes: 2
Views: 5062
Reputation: 1074
On component mount call loadDataFromServer()
at a set interval and update the components state. This will re-render the component with the updated state data.
loadDataFromServer(component, apiUrl) {
axios.get(apiUrl).then(function(res) {
var dataList = res.data.list;
component.setState({
data : dataList
});
});
}
componentDidMount() {
this.loadDataFromServer(this, this.state.dataEndpointUrl);
setInterval(this.loadDataFromServer.bind(null, this, this.state.dataEndpointUrl), this.state.pollInterval);
}
Upvotes: 0
Reputation: 281726
The problem is your get request is only getting fired on initial load. You need to fetch data regularly. Say if you want to fire the request initially and then after every 2 seconds then you can do something like this. I suppose this will solve your problem
componentDidMount: function() {
this.startPolling();
},
componentWillUnmount: function() {
if (this._timer) {
clearInterval(this._timer);
this._timer = null;
}
},
startPolling: function() {
var self = this;
setTimeout(function() {
if (!self.isMounted()) { return; } // abandon
self.poll(); // do it once and then start it up every 2 seconds
self._timer = setInterval(self.poll.bind(self), 2000);
}, 1000);
},
poll: function() {
var self = this;
$.get(this.props.source, function (data) {
console.log(" Data value :"+data);
var old = data.replace("//", "");
self.setState({
stock: JSON.parse(old)
});
}.bind(this));
}
Upvotes: 1