Search code examples
javascriptreactjsreactjs-fluxflux

React.js & Flux - where is the best place to register Websocket event (receive data)


I'm trying to write a simple application that should display a list of items received from Firebase DB, using Websockets. To receive data I should listen to firebase events, something like this:

var ref = new Firebase("firebase-url-here");

ref.on('value', function(snap) {
    console.log(snap.val());
});

My question is - where is the correct location to register this event?

I read this great article about Flux - in the comments section there is an answer from Facebook engineer saying receiving data will be via store's getData method. On the other hand, on Facebook's Todolist tutorial there is an option for 'handleServerAction' which should handle server actions. I understand the concept that actions should be dispatched from view and from server (as view actions and server actions).

View actions will be dispatched from user interactions on the view file. I do not understand where is the place to dispatch server actions from (assuming I want to use the 'handleServerAction' method)


Solution

  • That's how I'd do it (in case of Flux): You should put your WebSocket into Web API module. Create socket init action (to initialize WebSocket) and push action (to send data via socket). Make Web API module to dispatch an action on data income, listen for this action in the store and update the store once you get some data. Then you can dispatch init action from within root component and listen to store changes in components where you need the data. Also you can dispatch push action when you need to send data over the socket.