Redux-React Single File Example

The following code in a single file is meant to help you understand how to implement redux-react.

const redux = require('redux');
const logger = require('redux-logger').createLogger();
const applyMiddleware = redux.applyMiddleware;

// constants are used here to name actions:
const CAKE_ORDERED = 'CAKE_ORDER';
const CAKE_RESTOCKED = 'CAKE_RESTOCKED';
const ICECREAM_ORDERED = 'ICECREAM_ORDERED';
const ICECREAM_RESTOCKED = 'ICECREAM_RESTOCKED';

// action creators:
const orderCake = (quantity = 1) => {
  return {
    type: CAKE_ORDERED,
    payload: quantity,
  };
};

const restockCake = (quantity = 1) => {
  return {
    type: CAKE_RESTOCKED,
    payload: quantity,
  };
};

const orderIceCream = (quantity = 1) => {
  return {
    type: ICECREAM_ORDERED,
    payload: quantity,
  };
};

const restockIceCream = (quantity = 1) => {
  return {
    type: ICECREAM_RESTOCKED,
    payload: quantity,
  };
};

const initialCakeState = {
  numOfCakes: 10,
};

const initialIceCreamState = {
  numOfIceCreams: 20,
};

// definition: reducer = (previousState, action) => newState
const cakeReducer = (state = initialCakeState, action) => {
  switch (action.type) {
    case CAKE_ORDERED:
      return {
        ...state,
        numOfCakes: state.numOfCakes - action.payload,
      };
    case CAKE_RESTOCKED:
      return {
        ...state,
        numOfCakes: state.numOfCakes + action.payload,
      };
    default:
      return state;
  }
};

// definition: reducer = (previousState, action) => newState
const iceCreamReducer = (state = initialIceCreamState, action) => {
  switch (action.type) {
    case ICECREAM_ORDERED:
      return {
        ...state,
        numOfIceCreams: state.numOfIceCreams - action.payload,
      };
    case ICECREAM_RESTOCKED:
      return {
        ...state,
        numOfIceCreams: state.numOfIceCreams + action.payload,
      };
    default:
      return state;
  }
};

// application state is maintained using reducers
const rootReducer = redux.combineReducers({
  cake: cakeReducer,
  iceCream: iceCreamReducer,
});

// global store with a logger middleware
const store = redux.createStore(rootReducer, applyMiddleware(logger));

console.log('the initial state: ', store.getState());

// unsubscribe is returned from the store.subscribe method
const unsubscribe = store.subscribe(() => {});

// store.dispatch(orderCake(3));
// store.dispatch(restockCake(4));

// alternative method to dispatch; but not necessary
const actions = redux.bindActionCreators(
  { orderCake, restockCake, orderIceCream, restockIceCream },
  store.dispatch
);

actions.orderCake(3);
actions.restockCake(4);

actions.orderIceCream(3);
actions.restockIceCream(4);

unsubscribe();

The example code was taken from lessons provided in the Codevolution series on YouTube.