NiRR
NiRR

Reputation: 5012

Stateless Event Listeners in React Redux

I need to add functionality into my react/redux application that is event based.

I'm using redux and I have reducers that change my application state on events through actions. Some actions for example: (USER_CLICKED_BUTTON, AJAX_CALL_STARTED, AJAX_CALL_ERROR, AJAX_CALL_SUCCESS)

I want to add listeners to these events and do some work that isn't state related, specifically, call another API like analytics.

Does it make sense to add another "reducer" with no real state, that simply listens to these actions and acts (for example call ga(...)?)

something like this:

var Actions  = require ('../actions/actionTypes');

var gaReducer = function(state, action) {
    switch (action.type){
        case Actions.USER_CLICKED_BUTTON: 
               ga('send', 'event', 'user-clicked-button');
               break;
    }

    return state;

}

Upvotes: 0

Views: 110

Answers (1)

meleyal
meleyal

Reputation: 33310

This sounds like a good case for middleware. Check out https://github.com/evgenyrodionov/redux-logger for an example.

Then your store might look something like:

const middleware = [
  myAnalyticsMiddleware()
];

export default createStore(reducer, applyMiddleware(...middleware));

Upvotes: 1

Related Questions