PranavPinarayi
PranavPinarayi

Reputation: 3207

Difference Between a Redux middleware and reducer accepting all actions

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

Upvotes: 2

Views: 760

Answers (2)

Pranay Tripathi
Pranay Tripathi

Reputation: 1882

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.

Upvotes: 1

Saad Khan
Saad Khan

Reputation: 108

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.

Upvotes: 3

Related Questions