Application State with Redux - andrewkyllo-401-advanced-javascript/seattle-javascript-401d34 GitHub Wiki

  • Managing state with Redux requires the combination of 3 distinct aspects into a Store which all components can access as the please
    • State
    • Reducers (strategies to alter state)
    • Actions (methods that get dispatched or run, which trigger associated reducers

Redux Store

  • The store is where your application state is stored.
  • Reducers hold and manage state
let initialState = { customerId: null, items: [] };

const myReducer = (state = initialState, action) => {
  let { type, payload } = action;

  switch (type) {
    case 'INITIALIZE':
      return {customerId: payload.id};

    case 'ADD_ITEM':
      return { items: [...items, payload.item] };

    case 'CLEAR':
      return initialState;

    default:
      return state;
  }
};
  • An action creator function as shown below always returns an action object with the action type to perform and the data to perform it with.
  • When your component wants to modify state, it dispatches an action and sends whatever payload it needs to the reducer

When an action is dispatched, a reducer responds to it and receives that payload, where it then operates on state using its

// actions.js
const newCart = customer => {
  return {
    type: 'INITIALIZE',
    payload: customer,
  };
};