Search code examples
javascriptreactjsreduxanalyticsreactjs-flux

In Flux architecture, how do you manage analytics tracking?


Let's say I'm building a single page application like Airbnb. One thing that would be good in such application is to track when someone creates an account.

For the tracking part, there are a lot of services that would help (google analytics, segment, etc).

For example, to track an event using react-ga you simply can use the following:

ReactGA.event({
  category: 'User',
  action: 'Created an Account'
});

But my question is... how this should be done in a flux architecture?

Should I dispatch an action and add a middleware for this action? Or just call that function directly inside of signUp action?


Solution

  • A few times I had to code very similar thing for services like Intercom. I used Redux at that time. In event-driven architecture, which Redux based apps are, you can do it in a very attractive way just by using middlewares.

    In my case, I have noticed that I already have all required actions and all I need is just send a request to an analytics too after some action was triggered.

    Something like this:

    function sendIntercomRequest(action) {
      // send a request to analytic tool here
    }
    
    const intercomMiddreware = store => next => action => {
      switch (action.type) {
        // take required events
        case actionTypes.SIGN_IN_SUCCESS:
        case actionTypes.SIGN_OUT_SUCCESS:
          sendIntercomRequest(action.type);
          break;
      }
    
      return next(action);
    };