I am new to ReactJS and exploring it for an application that requires real time data.
Lets say I have "n" components that have to show the real time data (1 second update). The app should consolidate all the "n" components' related "tags" and call the webserver which gives the real time data for all the "tags"( I cannot make a call from each component as it will be a huge load. So I have to consolidate and make a single call).
There is a component "RealTimeDataFetcher" which has a timer and invokes an action "GETLIVEDATA" every second. This action calls the webservice and returns the response (Using thunk). DataReducer returns the updated state and all the "n" components uses the MapStateToProps for getting the live data.
Actions
export const subscribeForData = tag =>{
return {type : 'SUBSCRIBE' , payload : tag}
}
export const getLiveData = tag[] =>{
const response = await makeServiceCall(tag[]);
dispatch({ type: 'LIVE_DATA', payload: response.data });
}
Reducer
export const liveData = (livedata, action){
// update state for live data
}
export const subscribedTags= (tags, action){
// update state for subscribed tags
}
RealTimeDataFetcher
class RealTimeDataFetcher extends React.Component{
componentDidMount(){
// call subscribeData for fetching livedata for "tags"
}
}
function mapStateToProps (state){
return { subscribedTags: state.subscribedTags};
}
connect(mapStateToProps,{...})(RealTimeDataFetcher)
Component
class SomeComponent extends React.Component{
ComponentDidMount(){
this.props.subscribeForData("tag");
}
ComponentDidUpdate(){
// I will get the live data here.
}
}
function mapStateToProps (state){
return { liveData: state.liveData};
}
connect(mapStateToProps,{...})(SomeComponent )
This approach is working. But I am not sure if this is the right way to get the real time data.
Is there any other approach that I can look into.