Detuned
Detuned

Reputation: 3768

Redux middleware logic

I'm having a hard time understanding redux middleware and exactly how it gets configured within the Redux store. For example, I have the following examples

const store = compose(
  resetRedux('LOGOUT_USER'),
  applyMiddleware(...middlewares),
)(createStore)(rootReducer, initialState);

resetRedux is a middleware that basically resets the entire redux store when the string LOGOUT_USER is dispatched. This works great, however, if I put a console.log within the resetRedux middleware, it only gets called once, which is strange, considering I'd imagine that action needs to be checked every time in order to be able to decide whether to reset the store.

export default function resetMiddleware(types = ['RESET']) {
  return (next) => (reducer, initialState) => {
    const resetTypes = Array.isArray(types) ? types : [types];
    console.log('THIS IS ONLY CALLED ONCE??!')
    const enhanceReducer = (state, action) => {
      if (~resetTypes.indexOf(action.type)) {
        state = undefined;
      }
      return reducer(state, action);
    };
    return next(enhanceReducer, initialState);
  }
};

So, I'm curious how this is working when the console.log is only called once.

Upvotes: 1

Views: 604

Answers (2)

markerikson
markerikson

Reputation: 67627

You're confusing and conflating "middleware" and "store enhancers". The resetRedux piece that you've written is actually a "store enhancer", not a middleware.

A real middleware would have its main body executed for every action that is dispatched. The store enhancer itself is evaluated/executed once, at the time of store creation. The reducer you're returning will be executed for every action, because you're creating a function that wraps around whatever the "real" reducer is that's provided to createStore.

As an addendum, the Redux Tutorials#Implementation Walkthroughs section of my React/Redux links list has several articles that explain how middleware work in Redux.

Upvotes: 2

Avraam Mavridis
Avraam Mavridis

Reputation: 8940

Thats what compose does, it takes your passed functions and create a new function that "compose" them.

Arguments

(arguments): The functions to compose. Each function is expected to accept a single parameter. Its return value will be provided as an argument to the function standing to the left, and so on. The exception is the right-most argument which can accept multiple parameters, as it will provide the signature for the resulting composed function. Returns

Returns (Function): The final function obtained by composing the given functions from right to left.

You can check the source code here

Its a typical utility in functional programming, e.g. lodash's also provide it, underscore as well

Upvotes: 1

Related Questions