Reputation: 2753
I've inherited a Redux codebase, and I found a bit of the code that violates Redux's cardinal rule: no side effects in reducers.
Specifically, there's a tracking
reducer and it looks something like this:
function tracking(state = {}, action) {
function sendEvent(event, data) {
// API call here to send a tracking event
}
switch (action.type) {
case TRACK_FRIEND_REQUEST:
sendEvent('track-friend-request', action.payload);
return state;
case TRACK_LINK_CLICK:
sendEvent('link-click', action.payload);
return state;
}
}
This is obviously wrong; the state is meaningless and it only exists for its side-effect. The correct solution (IMO) would be to create a tracking
middleware that listens for actions with a meta
property, and attach meta
properties to the actual events, instead of creating these specialized track events.
Surprisingly, though, I can't find any real consequences of using it this way, and I'm having a hard time justifying why it's worth the effort to fix it (there are a lot of these tracked events, so it would be a fair bit of work).
The only potential problem I see is that, when using the devtools, events would get re-sent whenever you toggle the action. We already ignore tracking actions in dev mode, though, so this isn't a concern.
Are there other reasons that this code would cause real-world problems that I'm not aware of?
Upvotes: 3
Views: 103
Reputation: 67499
Yep, you're dead-on. The primary issue would be with debugging while using the Redux DevTools. Flipping back and forth between previously dispatched actions would cause those actions to be dispatched again through the reducers, and thus re-trigger this behavior.
And yes, the "correct" place for this sort of thing would be a middleware.
Upvotes: 2