2

In my redux project, I want to check something ( for example network connection ) in every action dispatch. Should I implement using a reducer which accepts all type of actions( without type checking ) as given below

export default (state = defaultState) => ({
    ...state,
    neworkStatus: navigator.onLine
})

or with a middleware.

const NetworkMiddleware = store => next => (action) => {
    const result = next(action)
    const state = store.getState()
    if (navigator.onLine && !state.NetworkDetector.networkStatus) next({ type: 'NETWORK_SUCCESS' })
    if (!navigator.onLine && state.NetworkDetector.networkStatus) next({ type: 'NETWORK_ERROR' })
    return result
}

export default NetworkMiddleware;

what is the difference between these two implementations

PranavPinarayi
  • 3,037
  • 5
  • 21
  • 32

2 Answers2

3

It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more.

I think it would be better to use a middleware to analyse network activity. Read these Redux docs for further information.

Saad Khan
  • 108
  • 1
  • 1
  • 10
1

A middleware in redux intercepts actions and performs some specific activity before it goes to the reducer to update the state. Middleware is meant to perform such actions without making the changes to the state in store. If you perform such tracking or modification by writing a reducer, you end up maintaining a state in the store for this activity which may have nothing to do with your component update or re-rendering. This is not a good practice I suppose and doesn't go as per the framework design. So it is better to achieve it via use of a middleware.

Pranay Tripathi
  • 1,614
  • 1
  • 16
  • 24
  • Yes, I think that is the point: middleware isn't intended to leave a step in the state-change-history. – lfree Oct 10 '18 at 04:00