Monday, April 23, 2018

React app with Redux and Redux Observables

Technologies

  • React js (for UI)
  • Redux (for state management; actions and reducers that set state)
  • React-Redux (for connecting Redux to React; redux actions and arbitrary properties that can be set as properties of the component; Provider component makes the store available to all components)
  • Redux Observable (for linking RxJS to Redux; applyMiddleware to redux store; takes care of RxJS subscriptions and un-subscribe)
  • RxJS (Reactive programming based on observables)

Packages

yarn add redux react-redux rxjs redux-observable

// rxjs requires tslib
yarn add tslib

The Idea

  • Redux Action is dispatched
  • Received by the Reducer
  • Since there is redux observable middle-ware applied, the action is then received by the Epic (redux observable action handler)
  • Epic is now free to either handle that action or not based on the action.type
  • Epic can fire an entirely new action that is then received by the Reducer
  • Which in turn may possibly be handled by another Epic (or not)

Data Retrieval Flow

Epics (Redux observables) are very good at handling asynchronous operations, errors, and mapping results.
  • An redux action is invoked (for example, by clicking a button)
  • Action is handled by the reducer (which can possibly place a loading message in the store, which in turn my be displayed by react component to the user)
  • The same action can then be optionally handled by an Epic (redux observables middleware)
  • The Epic can perform the asynchronous data fetch operation (ajax, for example)
  • When finished, Epic can produce another action with the data retrieved
  • That action is then handled by the reducer, that may remove the loading message from the store and set retrieved value in the store.
  • The retrieved value in the store may then be reflected in the react component