user3224271 user3224271 - 2 months ago 5x
Javascript Question

How to divide the logic between Redux reducers and action creators?

I have some logic that I've put in the reducer which I'm thinking should be possibly put in the Action and passed down?

Is it best practice to put this sort of stuff in the actions or reducer?

Working example here.

Reducer code:

function Card() {
this.card = (Math.random()*4).toFixed(0);

Card.prototype = {
getRandom: function(){
var card;
switch (this.card) {
case '1':
card = 'heart';
case '2':
//card = 'diamonds';
card = 'heart'; // weight the odds abit
case '3':
card = 'club';
case '4':
card = 'spade';
card = 'heart';
return card;

var dealer = {
deal: function(){
var results = [];
for(var i = 0; i <4; i++){
var card = new Card();
return results;

const initialState = {
count: 0,
data: []

function counter (state = initialState, action) {
let count = state.count
switch (action.type) {
case 'increase':
return Object.assign({}, state, {
count: state.count+1
return state


Your reducer must be pure. Currently it is not pure. It calls deal() which calls getRandom() which relies on Math.random() and thus is not pure.

This kind of logic (“generating data”, whether randomized or from user input) should be in the action creator. Action creators don’t need to be pure, and can safely use Math.random(). This action creator would return an action, an object describing the change:

  type: 'DEAL_CARDS',
  cards: ['heart', 'club', 'heart', 'heart']

The reducer would just add (or replace?) this data inside the state.

In general, start with an action object. It should describe the change in such a way that running the reducer with the same action object and the same previous state should return the same next state. This is why reducer cannot contain Math.random() calls—they would break this condition, as they would be random every time. You wouldn't be able to test your reducer.

After you figure out how the action object looks (e.g. like above), you can write the action creator to generate it, and a reducer to transform state and action to the next state. Logic to generate an action resides in action creator, logic to react to it resides in the reducer, reducer must be pure.

Finally, don’t use classes inside the state. They are not serializable as is. You don’t need a Card class. Just use plain objects and arrays.