Creating a Reducer

In notebook:
FrontEndMasters Intermediate React
Created at:
2019-06-25
Updated:
2019-08-15
Tags:
React libraries JavaScript

https://frontendmasters.com/courses/intermediate-react-v2/creating-a-reducer/

Creating the reducers

Creates new folder, reducers

   //    ****        reducers/index.js        ****

import { combineReducers } from "redux";
import location from "./location";

export default combineReducers({
  location: location
});

Creating one reducer

Redux is a big tree of objects, the state of the app. We will make the ./location reducer only affect the location piece of the state tree.

Then, do the location reducer

   //    ****        reducers/location.js        ****

 // adding a default value for state...
export default function location(state = "Seattle, WA", action) {
  switch (action.type) {
    case "CHANGE_LOCATION":
      return action.payload;
    default:
      return state;
  }
}

the action object

The action object above is provided by redux.

the reducers should be pure functions, in the case this is very well testable.

You should always return a state this is why switch with a default case is great.

The payload property

While the action property is a hard requirement, payload is part of the flux standard action. It's available as a GitHub repo. It's a description of the action shapes.

Theme js

  //    ****        reducers/theme.js        ****

export default function theme(state = "darkblue", action) {
  switch (action.type) {
    case "CHANGE_THEME":
      return action.payload;
    default:
      return state;
  }
}

Brian and the DRY principle

His rule of thumb is write the same code three times and if you need the fourth time, only then abstract it out.

Then use theme

  import { combineReducers } from "redux";
import location from "./location";
import theme from "./theme";

export default combineReducers({
  location,
  theme
});