I have an application which uses react with flux and a webserver that stores all the data and notifies all the subscribers when an update has occured through a websocket.
My problem is that when my component triggers an action the new state is sent to the webserver through the socket and to the store at the clients browser, but then my server will send a message to all subscribers that this is the new state for this component so that all clients gets updated but this causes the client to send a new update that the state has changed. And this goes in a infinite loop where client send to server and server responds with the update to all subscribers and since it is an update the client sends the new state to the server again...
utils/WebAPI:
var socket = new SockJS("http://localhost:8080/stomp");
var client = Stomp.over(socket);
module.exports = {
sendUpdate: function(update){
if(client.connected){
client.send("/app/hello", {}, JSON.stringify(update));
}
},
getUpdates: function() {
client.connect({}, function() {
client.subscribe("/topic/hello", function(message) {
var data = JSON.parse(message.body);
MyActions.updateState(data.id, data.update)
});
});
}
};
MyActions:
var AppDispatcher = require('../dispatcher/AppDispatcher');
var FunctionConstants = require('../constants/FunctionConstants');
// Define actions object
var MyActions = {
updateState: function(id, update) {
AppDispatcher.handleAction({
actionType: FunctionConstants.STATE_UPDATED,
id: id,
update: update
})
}
};
module.exports = MyActions;
The update function in my store:
var WebAPI = require('../utils/WebAPI');
var _ = require('underscore');
// Define initial data points
var _data = {};
function updateFunction(id, data) {
_data[id] = data
var update = "{\"actionType\": \"STATE_UPDATED\", \"id\": \""+id+"\", \"update\": "+JSON.stringify(data)+"}";
WebAPI.sendUpdate(JSON.parse(update));
}
...
And finally my component:
let React = require('react');
var MyActions = require('../../../actions/MyActions');
var WebAPI = require('../../../utils/WebAPI');
//Subscribe for updates sent from server
WebAPI.getUpdates();
let FunctionComponent = React.createClass({
newState: function(data){
MyActions.updateState(this.props.id, data);
},
render() {
var d = this.props.data;
d.count++;
return (
<div>
<h1>{this.props.id}</h1>
<div>{this.props.data}</div>
<button onClick={this.newState(d)}
</div>
)
}
});
module.exports = FunctionComponent;
How can I overcome this problem that causes an infinite loop when my component calls any action and the server sends an update to all subscribers?