Search code examples
javascriptreactjsfluximmutable.js

How to feed dependencies between Flux stores using Immutable.js?


I have a simple chat application going on and the following stores:

  • MessageStore - messages of all users/chat groups
  • ChatGroupStore - all chat groups
  • UserStore - all users in general

I'm using immutable.js to store data. The thing is, MessageStore needs to use data from ChatGroupStore and UserStore, each message is constructed like this:

{
    id: 10,
    body: 'message body',
    peer: {...} // UserStore or ChatGroupStore item - destination
    author: {...} // UserStore or ChatGroupStore item - creator of the message
}

How am I suppose to update MessageStore items according to ChatGroupStore and UserStore update?

I was using AppDispatcher.waitFor() like this:

MessageStore.dispatchToken = AppDispatcher.register(function(action) {
    switch(action.actionType) {
    case UserConstants.USER_UPDATE:
        AppDispatcher.waitFor([
            UserStore.dispatchToken
        ]);

        // update message logic
        break;
    }
});

From my point of view I would have to wait for the UserStore to update and then find all the messages with the updated user and update them. But how do I find the updated peer? I think a search in UserStore by reference wouldn't be enough since immutable data doesn't keep the reference when data changes, then I would have to apply more on queries. But then I would have to apply query logic of other stores inside MessageStore handler.

Currently I'm storing peers as a reference inside each message, maybe should I change to just:

{
    id: 10,
    peer: {
        peerType: 'user', // chatGroup
        peerId: 20
    }
}

Would be great if anybody could shed some light about it. I'm really confused.


Solution

  • The best option I can see as a solution in all occasions is not to keep related data nested and to avoid transformations on data that comes from server, this will reduce the amount of work I need to do to keep the data up to date at all times. Then in your view, all you have to do is to subscribe to changes and put together the necessary data.

    Alternative to Flux

    There's also a good and well maintained state container solution called Redux which I suggest everyone to at least try. It has only one store and combines the whole state into a single deep object, although you can create each reducer separately. It also has a good way to integrate it with React, see Usage with React.