Flux architecture circular dependency
Asked Answered
A

1

6

I have started learning Facebook's Flux architecture. I am trying to make a simple login screen. I have followed the flux-chat sample app to create the screen. I have a problem of circular dependency between ServerActionCreator and WebAPIUtils. Please see the code below.

ServerActionCreator.js

var AppDispatcher = require('../dispatcher/AppDispatcher');
var Constants = require('../constants/Constants');
var WebAPIUtils = require('../utils/WebAPIUtils');

var ActionTypes = Constants.ActionTypes;

module.exports = {
    receiveLoginStatus: function(status){
        AppDispatcher.handleServerAction({
            type: ActionTypes.RECEIVE_LOGIN_STATUS,
            status: status
        });
    },
    
    loginSubmit: function(data){
        WebAPIUtils.login(data);
    }
}

WebAPIUtils.js

var ServerActionCreator = require('../actions/ServerActionCreator');

module.exports = {
    login: function (data) {
        //Mock server API call
        var status = JSON.parse('{"status":"success"}');
        ServerActionCreator.receiveLoginStatus(status);
    }
};

As you can see ServerActionCreator depends on WebAPIUtils and WebAPIUtils depends ServerActionCreator.

I think, due to circular dependency WebAPIUtils becomes an empty object and I am getting "undefined is not a function" error when loginSubmit function in ServerActionCreator is called. Screenshot below.

enter image description here

How to handle this scenario? or Is there any alternative way? Any help is much appreciated.

Atheling answered 27/12, 2014 at 5:12 Comment(0)
F
4

Whenever you have a circular dependency between modules, a common solution is to either combine the modules or to create a third entity that will break the cycle.

In your case, I'd argue that you could move loginSubmit to a different action creators module. It's actually a user action, not a sever action, anyway. So maybe loginSubmit could go in UserActionCreators.js along with any number of other user action creator methods.

Another solution to your problem (and to circular dependencies in general) is to make your methods more pure, removing dependencies and instead passing in dependencies as arguments. So WebAPIUtils.login() could take a second argument, which would be the success callback. Thus:

WebAPIUtils.login(data, ServerActionCreator.receiveLoginStatus)
Fowkes answered 28/12, 2014 at 4:33 Comment(1)
Since the login action is intiating a server request I was under the impression that it has to be in ServerActionCreator. Anyways, I've used your second solution and it's working fine. Thanks for your help.Atheling

© 2022 - 2024 — McMap. All rights reserved.