Circular Dependence of Stream Architecture

I began to study the architecture of Facebook Flux. I am trying to make a simple login screen. I created a flux-chat screen sample. I have a cyclical dependency problem between ServerActionCreator and WebAPIUtils. See 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 on ServerActionCreator.

I think, due to the cyclical dependency, WebAPIUtils becomes an empty object, and I get the error "undefined is not a function" when calling the loginSubmit function in ServerActionCreator. Screenshot below.

enter image description here

How to cope with this scenario? or is there an alternative way? Any help is greatly appreciated.

+6
source share
1 answer

Whenever you have a circular relationship between modules, the general solution is to either combine the modules or create a third object that breaks the loop.

In your case, I would say that you can move loginSubmit to another module of action creators. In any case, this is a user action, not an action on a smaller one. Therefore, it is possible loginSubmit can enter UserActionCreators.js along with any number of other methods for creating custom actions.

Another solution to your problem (and for circular dependencies in general) is to make your methods cleaner, remove the dependencies, and instead pass in the dependencies as arguments. So WebAPIUtils.login() can take a second argument, which will be a successful callback. In this way:

 WebAPIUtils.login(data, ServerActionCreator.receiveLoginStatus) 
+4
source

Source: https://habr.com/ru/post/980194/


All Articles