I am trying to notify clients when the database has been updated so that the front end can present the correct state to users. The functionality I want is for sockets to send a message that will trigger the application to make a get request for the updated state. Where should the socket listener be on the front-end?
1)Api-Utils 2)Relevant Store(s) 3)Server-Action Creator
Currently Api-Utils does all the actual fetching of data from the server, the Server-Action-Creator gets called when the data is retrieved and the stores are notified via the dispatcher. The stores just hold our data, give it to components, and listen for when the dispatcher has a new payload.
TL;DR; Your client-side socket listeners should be 'dumb' listeners, who's sole task is to pass data received on to actions. Logic on what to do with that data should be inside of the action.
The socket listener should be outside of flux, and execute actions as data events are received from the server.
For example, here's my client.jsx file (edited with partial pseudocode, for readability), using Fluxible's rehydrate
function to inject founding state into my client-side app):
import Socket from 'socket.io-client';
import BaseClient from './utils/baseClient';
// Fluxible
import {createElementWithContext} from 'fluxible-addons-react';
// Components
import Loading from './components/loadingComponent.jsx';
class Client extends BaseClient {
sockets() {
this.socket = Socket();
this.socket.on('someEvent', (data)=>{
this.context.executeAction('nameOfSomeAction', data);
});
}
constructor(component) {
super(component);
this.app.rehydrate(window.App, (e, ctx)=> {
this.context = ctx;
this.sockets();
React.render(createElementWithContext(ctx), document.getElementById('main'));
});
}
}
new Client(Loading);
When data is received from the server, it's sent to the action, which in turn decides what to do with that data (call third-party APIs, dispatch to store, etc).