About Redux Data Processing
Redux introduced a way to better separate our focus, when we code different parts of an App:
- UI
- what
Datais needed- from
ReduxStore - trigger
renderon changes
- from
- how
UIrender & layout- initial
render - follow-up updating
render
- initial
- when and what
Actionis accepted- from user input, connection or other input source
dispatchtoReduxStore
- what
- Data
- what type of
Actionis accepted, and how the Data updates- by defining
ReduxReducer
- by defining
- what type of
Data processing in Redux
More on the Data part and Redux. But first, some basic concept:
- The Data is Stored in
ReduxStore, calledState - the
Stateis an immutable Object - the
Stateshould be holding all the Data required to render theUI - the
Stateupdates first, then theUIrender and reflect the change - the
Statecan only be updated by theReduxReducer - the
ReduxReduceris a Function that takesActionas input - the
ReduxReduceris a pure Function - the
Actionis an Object containingtypeandpayload
So it all starts with an Action, and ends with a new ReduxStore.State.
More specifically: from store.dispatch(action) to some code like store.state = nextState.
What happens between can be simplified as:
// in Redux Reducer
nextState = reducerFunction(actionObject)
Sooner of later you'll find: it's hard to all the complex and async Data processing code into a pure Function and an Object.
There should be something allows extra codes to fits between Action and ReduxReducer,
and thus ReduxMiddleware.
Data processing in ReduxMiddleware
Browsing the npm, and there's a lot of ReduxMiddleware to pick from.
Mainly the Data processing ReduxMiddleware aimed to :
- provide a way to process Data asynchronously
- make the async code easier to read and write
For async code: callback, Promise, and Generator can be used.
redux-thunk choose the most simple and direct callback.
It's a good start, but to well organize the code needs al lot more work.
redux-saga use Generator to pack the async logic.
It do works better with async than callback.
Data processing with Redux-Service:
redux-service borrowed a bit of both, and add some new:
callbackfirst,Generatorlater.- allow Block Action from further processing
Combine the callback and allow Block Action adds an additional bonus:
coordinate the logic.
Pack the async logic in Generator,
and use callback to filter, redirect, pre-process the Action.
Data processing with Redux-Service:
// in Redux-Service Middleware
const entryFunction = reduxService.entryMap[actionObject.type]
if (entryFunction && entryFunction(redux.store, actionObject)) return // Blocked Action
for (const service of reduxService.serviceList) {
if (service.accept(actionObject.type) && service.generator.next(redux.store, actionObject)) return
}
// in Redux Reducer
nextState = ReducerFunction( ActionObject )